Luke1988
Luke1988

Reputation: 2128

Angular: Subject behaviour different when using forkJoin

Folks, can anyone explain this behaviour?

This is working:

this.sessionService.current$.subscribe(session => { console.log('WORKING', session); });

But this is NOT working:

forkJoin([
      this.sessionService.current$
    ])
      .subscribe(([
        session
      ]) => {
        console.log('NOT WORKING', session);
...
    

After a little change got it working:

forkJoin([
      this.sessionService.current$.pipe(take(1))
    ])
      .subscribe(([
        session
      ]) => {
        console.log('WORKING', session);
...
    

current$ property in SessionService is defined like this:

private readonly subject$: Subject<Session> = new BehaviorSubject<Session>(null);
public readonly current$: Observable<Session> = this.subject$.asObservable();

there is then a init() method where I GET data over http and emit to this.subject$;

Thanks a lot for a right direction!

Upvotes: 2

Views: 599

Answers (1)

martin
martin

Reputation: 96979

forkJoin emits only after all its source Observables emit at least once and all complete. So when you're using Subject as a source Observable for forkJoin() then by adding take(1) you force it to complete and therefore forkJoin emits as well and then completes.

Upvotes: 3

Related Questions