laprof
laprof

Reputation: 1344

Chaining subscription to multiple observables with parameter

I would like to subscribe two observables one after the other. The order is important and must be kept. The first observable returns a result itemId which must be passed to the second subscription. Currently, I use nested subscriptions, which is not very nice. What is the cleanest way to implement this?

// 1
this.widget$
  .subscribe((widget) => {
    const itemId: number = widget.data[0].itemId;

    // 2
    this.store
      .select(DeviceHistoryStore.getItemHistoryEntries(this.deviceId, itemId))
      .subscribe((deviceHistory) => {
        const name = widget.name; 
        // Run code
    });
});

Upvotes: 0

Views: 337

Answers (1)

Tobias S.
Tobias S.

Reputation: 23825

Simply use a SwitchMap.

this.widget$.pipe(
    switchMap(widget => 
        this.store
            .select(DeviceHistoryStore.getItemHistoryEntries(
                this.deviceId, 
                widget.data[0].itemId
            ))
    )
).subscribe(deviceHistory => { /* ... */ )

Edit:

If you want to access widget in the subscribe callback:

this.widget$.pipe(
    switchMap(widget => 
        combineLatest([
            of(widget),
            this.store
                .select(DeviceHistoryStore.getItemHistoryEntries(
                    this.deviceId, 
                    widget.data[0].itemId
                ))
        ])        
    )
).subscribe(([widget, deviceHistory]) => { /* ... */ )

Upvotes: 6

Related Questions