How to use frokJoin Observable with custom event

I am using Subject of reactivex in an angular2 application for a signal event.

When I do something like this:

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, and then follow some steps. I found Observable.forkJoin, but I can't get it to work with themes. Code like this does not 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 in this matter, please.

Best regards Krzysztof Szewczyk

+1
source share
1 answer

In your case, you need to use the zip operator instead. This statement will combine the indicated observable sequences, while forkJoin runs all the observable sequences in parallel and collects their last elements.

Thus, the forkJoin operator forkJoin great with HTTP observables, for example, but not with objects.

Here is an example.

 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 .

+2
source

All Articles