RxJS 5, converting an observable to a BehaviorSubject(?)

蓝咒 提交于 2019-11-30 17:20:37

shareReplay should do what you want:

import 'rxjs/add/operator/shareReplay';
...
theValue$: Observable<boolean> = parent$.shareReplay(1);

shareReplay was added in RxJS version 5.4.0. It returns a reference counted observable that will subscribe to the source - parent$ - upon the first subscription being made. And subscriptions that are made after the source completes will receive replayed notifications.

shareReplay - and refCount in general - is explained in more detail in an article I wrote recently: RxJS: How to Use refCount.

I've implemented a method to convert Observables to BehaviorSubjects, as I think that the shareReplay method isn't very readable for future reference.

import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

export function convertObservableToBehaviorSubject<T>(observable: Observable<T>, initValue: T): BehaviorSubject<T> {
    const subject = new BehaviorSubject(initValue);

    observable.subscribe(
        (x: T) => {
            subject.next(x);
        },
        (err: any) => {
            subject.error(err);
        },
        () => {
            subject.complete();
        },
    );

    return subject;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!