本文介绍了如何在自己的事件中使用Observable的forkJoin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的angular2应用中使用了reactx的Subject来表示事件.

Im using Subject of reactivex in my angular2 app to signal event.

当我做这样的事情时:

let subject1 = new Subject<string>();
let subject2 = new Subject<string>();
subject1.subscribe(data=>console.debug(data));
subject2.subscribe(data=>console.debug(data));
subject1.next("this is test event1");
subject2.next("this is test event2");

一切正常,但我想等待两个事件触发,然后执行一些操作.我找到了Observable.forkJoin,但无法使其与Subjects一起使用.像这样的代码行不通

everything works fine, but I want to wait for both events to fire, then do some actions. I found Observable.forkJoin but I cant make it work with Subjects. Code like this dont work

Observable.forkJoin(
           subject1.asObservable(),
           subject2.asObservable()
        ).subscribe(
            data => {
              console.debug("THIS IS MY FJ");
              console.debug(JSON.stringify(data));
            },
            error=>console.error(error),
            ()=>{
              console.info('THIS IS MY FJ SUCCESS');
            }
        );

您能帮我解决这个问题吗?

Can you help me with this issue please.

最好的问候克尔兹斯托夫·塞夫奇克(Krzysztof Szewczyk)

Best RegardsKrzysztof Szewczyk

推荐答案

在您的情况下,您需要使用 zip 运算符.该运算符将合并指定的可观察序列,而 forkJoin 会并行运行所有可观察序列并收集其最后一个元素.

In your case, you need to use the zip operator instead. This operator will merge the specified observable sequences whereas the forkJoin one runs all observable sequences in parallel and collect their last elements.

因此 forkJoin 运算符可以很好地用于HTTP可观察对象,但不适用于主题.

So the forkJoin operator is fine with HTTP observables for example but not with subjects.

这里是一个样本.

export class App {
  subject1: Subject<string> = new Subject();
  subject2: Subject<string> = new Subject();

  constructor() {
    this.subject1.subscribe(data=>console.debug(data));
    this.subject2.subscribe(data=>console.debug(data));

    Observable.zip(
      this.subject1,
      this.subject2
    ).subscribe(
      data => {
        console.debug("THIS IS MY FJ");
        console.debug(JSON.stringify(data));
      },
      error=>console.error(error),
      ()=>{
        console.info('THIS IS MY FJ SUCCESS');
      }
  );
}

test() {
  this.subject1.next("this is test event1");
  this.subject2.next("this is test event2");
}

请参见相应的插件: https://plnkr.co/edit/X74lViYOgcxzb1AjC9dL?p=preview.

这篇关于如何在自己的事件中使用Observable的forkJoin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:14