合并/合并可观察量

时间:2017-07-18 21:41:46

标签: javascript typescript rxjs observable rxjs5

假设我正在开发一个聊天应用。我有可观察的threads$每隔 n 秒发出一个线程数组,observable offline$通知线程何时脱机,可观察online$通知线程何时成为在线:

enum ConnectionStatus { Offline = 0, Online }

interface Thread {
    id: string;
    status: ConnectionStatus
}

const threads$ = Observable
    .interval(n)
    .switchMap(() => Observable.create((observer: Observer<Array<Thread>>) =>
        getThreads((threads: Array<Thread>) => observer.next(threads))));

const online$ = Observable.create((observer: Observer<Thread>) =>
    onOnline((threadId: string) => observer.next({
        id: threadId,
        status: ConnectionStatus.Online
    })));

const offline$ = Observable.create((observer: Observer<Thread>) =>
    onOffline((threadId: string) => observer.next({
        id: threadId,
        status: ConnectionStatus.Offline
    })));

我想在规则之后组合这些流:threads$应该每隔n秒发出一次数组,但每当online$offline$发出时,我想要获取Array<Threads>的最新值(threads$)并通过更改一个线程的状态并立即发出映射集合来映射它。

我已经失去了与Rx的combineLatestmergeMapzip等相似的内容,所以如果有人可以帮我实现这方面的合并,我将不胜感激案例(更多的是Rx方式)

2 个答案:

答案 0 :(得分:1)

我认为你可以使用multicast()

这样做
const stop$ = Observable.merge(online$, offline$);
threads$
    .multicast(new Subject(), obs => Observable.merge(obs, obs.takeUntil(stop$).takeLast(1).map(...)))
    .subscribe(...);

我显然没有测试它,但也许它会推动你正确的方向。

答案 1 :(得分:0)

Array<Thread>threads$发出时,每当online$发出时,这会发出offline$

const threadUpdate$ = Observable.merge(
    threads$,
    Observable.merge(online$, offline$)
        .withLatestFrom(threads$,
            (thread, threads) => threads.map(t => {
                if(t.id === thread.id) {
                    t.status = thread.status
                }
            })));

请注意,threads$将继续发出,甚至可能与合并的online$ / offline$流同时发出。