Observable forkJoin not firing

后端 未结 5 707
暗喜
暗喜 2020-12-18 19:21

I\'m trying to user forkJoin on two Observables. One of them starts as a stream... If I subscribe to them directly I get a response, forkJoin isn\'

相关标签:
5条回答
  • 2020-12-18 19:52

    For me the combineLatest operator was the solution!

    0 讨论(0)
  • 2020-12-18 19:59
    Observable.forkJoin([
          _someService.getUsers(),
          _someService.getCustomers(),
        ])
          .subscribe((data: [Array<User>, Array<Customer>]) => {
            let users: Array<User> = data[0];
            let customer: Array<Customer> = data[1];
          }, err => {
          });
    
    
    
    
    
          //someService
            getUsers():Observable<User> {
              let url = '/users';
              return this._http.get(url, headers)
                .map(res => res.json());
            }
    
            getCustomers():Observable<Customer> {
              let url = '/customers';
              return this._http.get(url, headers)
                .map(res => res.json());
            }
    
    0 讨论(0)
  • 2020-12-18 20:01

    A very common problem with forkJoin is that it requires all source Observables to emit at least one item and all of them have to complete.

    In other words if this.statuses$ or this.companies$ doesn't emit any item and until they both complete the forkJoin won't emit anything.

    this.statuses$.subscribe(
        res => console.log(res),
        undefined,
        () => console.log('completed'),
    );
    
    0 讨论(0)
  • 2020-12-18 20:04

    forkJoin emits only when all inner observables have completed. If you need an equivalent of forkJoin that just listens to a single emission from each source, use combineLatest + take(1)

    combineLatest(
      this.statuses$,
      this.companies$,
    )
    .pipe(
      take(1),
    )
    .subscribe(([statuses, companies]) => {
      console.log('forkjoin');
      this._countStatus(statuses, companies);
    });
    

    As soon as both sources emit, combineLatest will emit and take(1) will unsubscribe immediately after that.

    0 讨论(0)
  • 2020-12-18 20:06

    The forkJoin didn't work so I used the below code to solve my problem. With mergeMap you can map the result of the outer subscription to the inner subscription and subscribe to it as you wish

    this.statuses$.pipe(
        mergeMap(source => this.companies$.pipe(
            map(inner => [source , inner])
            )
        )
    ).subscribe(([e , r]) => {
        console.log(e , r);
    })
    
    0 讨论(0)
提交回复
热议问题