1

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!

Luke1988
  • 1,850
  • 2
  • 24
  • 42

1 Answers1

3

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.

martin
  • 93,354
  • 25
  • 191
  • 226
  • Thanks! So, as far as I understand, forkJoin should be a cold observable and does not require an unsubscribe then? – Luke1988 Jan 08 '21 at 14:16
  • @Luke1988 forkJoin is often used with hot observables, just not with long-lived observables. Also, you should unsubscribe if there's a chance an inner observable may not complete or if you want to unsubscribe from the inner Observables because you're no longer interested in the result from forkJoin. – Mrk Sef Jan 08 '21 at 14:46
  • In current situation forkJoin makes absolutely no sense. Usually there is 2 or more observables and all except sessionService.current$ are cold http observables that fetch data from API. It makes sense then to wait until all observables finish because I need all the data to complete response. Therefore forkJoin. I wonder if unsubscribe from forkJoin subscription is required. [This post](https://stackoverflow.com/a/40430898/8244989) explains why forkJoin unsubscribe is not required – Luke1988 Jan 08 '21 at 15:43