How to convert Observable to ReplaySubject in RxJS?

Here is what I am doing now to convert Observable to ReplaySubject:

const subject = new Rx.ReplaySubject(1);

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

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

+4
source share
1 answer

You can use it only observable.subscribe(subject)if you want to send all 3 types of notifications, because the object already behaves as an observer. For instance:

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 the demo version: https://jsbin.com/bayewo/2/edit?js,console

However, this has one important consequence. Since you already subscribed to the Observable source, you turned it off from “cold” to “hot” (perhaps this does not matter in your use case).

+5

Source: https://habr.com/ru/post/1667189/


All Articles