How to use frokJoin of Observable with own event

你。 提交于 2019-12-24 17:47:59

问题


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

When I do something like that:

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");

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.

Best Regards Krzysztof Szewczyk


回答1:


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.

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

Here is a sample.

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");
}

See the corresponding plunkr: https://plnkr.co/edit/X74lViYOgcxzb1AjC9dL?p=preview.



来源:https://stackoverflow.com/questions/37069791/how-to-use-frokjoin-of-observable-with-own-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!