Reputation: 358
I have an issue with a switch map behavior.
I have selected spreadsheets ids, for each id I have a corresponding instance of UI component, I want to make a visual change at the beginning, then to do few google spreadsheet API calls and then make a visual change at the end. One note, that gapi client works outside of ngZone, to get it works correctly I'm using ngZone.zone.run.
const ids = [1,2]
function processSelectedIds(ids) {
from(ids)
.pipe(
switchMap(id => processId(id)),
)
.subscribe({
next: value => {
console.log('subscribe next')
this._state.ids = [] // clean selected ids
this.stateSubject.next([...this._state.data]) // trigger ui update
},
})
}
function processId(id) {
return of(id).pipe(
tap(_ => {
this.updateUI(id, STATE.start) // mutate state
this.stateSubject.next([...this._state.sheets]) // trigger ui update
console.log('before', id)
}),
switchMap(() => {
console.log('switchMap', id)
return getSpreadsheet(id)
}),
tap(_ => {
console.log('after', id)
this.updateUI(id, STATE.end) // mutate state
this.zone.run(() => { // because getSpreadsheet runs outside of NgZone
this.stateSubject.next([...this._state.sheets]) // trigger ui update
})
}),
)
}
getSpreadsheet(id) {
return forkJoin({
response1: apiCall1(id),
response2: apiCall2(id),
}).pipe(
map(response => {
return parseResponse(response)
}),
)
}
My issue that second tap inside processId doesn't trigger. This is how looks my output:
before, 1
switchMap, 1
before, 2
switchMap, 2
after, 2
subscribe next
I cannot figure out what is wrong here, I would appreciate any help on how to make it works. Thanks in advance for your help
Upvotes: 1
Views: 901
Reputation: 96909
It looks like the source Observable from(ids)
emits too fast and switchMap()
will unsubscribe before getSpreadsheet(id)
can emit.
So maybe you are looking for concatMap()
or mergeMap()
instead.
Upvotes: 1