問題描述
rxjs減少不繼續 (rxjs reduce does not continue)
我在 Angular 7 應用程序中有以下設置:
@Effect({dispatch:false})
LoadInstances$ = this.actions$.pipe(
ofType(fromAppAction.AppActionTypes.LoadInstances),
take(1), // <‑‑ solved my problem
switchMap((action: fromAppAction.LoadInstances) =>
this.entityService.GetInstances()
),
switchMap(instances=>from(instances)), // flatten the array to single values
flatMap( // combine the instance with its UserData
(inst)=>this.entityService.GetCurrentUserInfo().pipe(take(1)),
(inst,usr)=>({...inst, UserData:usr})
),
flatMap(
(inst)=>this.entityService.GetUserPersonalSettings(inst.id).pipe(take(1)),
(inst,settings)=>({...inst, Settings:settings})
),
tap(result=>console.log('before reduce:',result)), // <‑‑ this gets called 3 times (I have 3 instances)
reduce<Instance>((a, c) => [...a, c], []), // accumulate all results to one array
tap(result=>console.log('instances: ', result)), // <‑‑ this gets never called
...
本質上,我有一個實例數組,將它們展平,為每個實例調用 GetCurrentUserInfo 和 GetUserPersonalSettings,將結果添加為屬性到實例,然後想將它們累積回 Instance[]。
到目前為止,這有效,只是 reduce 函數不會繼續。我知道這是因為其他 observables 之一沒有完成。但怎麼可能呢?最初的 from(instances) 遍歷數組,然後應該完成,是嗎?並且對 GetPersonalSettings 的調用只是簡單的 httpClient.get() 調用,根據文檔,它是在成功調用後完成的單值可觀察對象。
有人可以幫助我嗎?
[編輯] 掃描在這裡不是一個選項,因為我需要完整的實例數組才能繼續。[Edit2] toArray 和 reduce 有同樣的問題,它只會在前一個 Observable(s?) 完成時才發出結果。
無論如何:我不想改變這個設置因為它基本上可以工作。我只想了解哪個 Observable 沒有完成以及為什麼。這將解決我的問題。
參考解法
方法 1:
Recently I learned about operator toArray, might simplify your code. You stream doesn't complete because stream before first switchMap
is not completed
/* What is here? Probably still open stream? */
switchMap((action: fromAppAction.LoadInstances) =>
this.entityService.GetInstances()
),
Quick try would be put first()
or take(1)
before first switchMap
(by joachim_b、Maksim Romanenko)