[英]Hybrid of mergeMap and concatMap in rxjs
我正在開發一個后端應用程序,並且我遇到了從用戶那里獲取事件的情況。 對於每個事件,我都會調用某個端點foo
。 如果我有來自同一用戶的多個事件,我想在上一次對foo
的調用完成后進行下一次foo
調用(concatMap 行為)。 同時,對於不同的用戶,調用必須並行完成(mergeMap 行為)。
在代碼中,它看起來像這樣:
const userEvent$: Observable<{userId: string}> = ...
const foo: (userId: string) => Observable<Response> = ...
let result$: Observable<Response> = ???
考慮使用GroupBy運算符,通過userId
對事件進行分組,接下來將concatMap
應用於組,以便同一組內的事件按順序執行,如下例所示:
userEvent$.pipe(
groupBy(item => item.userId),
mergeMap(group => group.pipe(concatMap(x => foo(x.userId))))
);
演示:
const { of, from } = rxjs; const { delay, tap, concatMap, mergeMap, groupBy } = rxjs.operators; function foo(userId, index) { return of(userId).pipe( delay(2000), tap(() => console.log("UserId: ", userId, ", Occurrences: ", index + 1)) ) } const userEvent$ = from([ { userId: 1 }, // <- first { userId: 2 }, // <- first { userId: 2 }, // <- second { userId: 3 },// <- first { userId: 1 }, // <- second { userId: 1 }, // <- third { userId: 2 }, // <- third { userId: 3 }, // <- second ]); userEvent$.pipe( groupBy(x => x.userId), mergeMap(group => group.pipe(concatMap((x,i) => foo(x.userId,i)))), ).subscribe()
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.2/rxjs.umd.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.