Search code examples
typescriptangularrxjsreactivex

How to use forkJoin of Observable with own event


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


Solution

  • 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.