rxjsrxjs5

How to convert an Observable to a ReplaySubject?


Here is what I'm doing now to convert an Observable to a ReplaySubject:

const subject = new Rx.ReplaySubject(1);

observable.subscribe(e => subject.next(e));

Is this the best way to make the conversion, or is there a more idiomatic way?


Solution

  • You can use just observable.subscribe(subject) if you want to pass all 3 types of notifications because a Subject already behaves like an observer. For example:

    let subject = new ReplaySubject();
    subject.subscribe(
        val => console.log(val),
        undefined, 
        () => console.log('completed')
    );
    
    Observable
        .interval(500)
        .take(5)
        .subscribe(subject);
    
    setTimeout(() => {
        subject.next('Hello');
    }, 1000)
    

    See live demo: https://jsbin.com/bayewo/2/edit?js,console

    However this has one important consequence. Since you've already subscribed to the source Observable you turned it from "cold" to "hot" (maybe it doesn't matter in your use-case).