Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an Observable to a ReplaySubject?

Tags:

rxjs

rxjs5

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?

like image 690
Misha Moroshko Avatar asked Jan 18 '17 22:01

Misha Moroshko


Video Answer


2 Answers

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).

like image 69
martin Avatar answered Oct 21 '22 10:10

martin


It depends what do you mean by 'convert'.

If you need to make your observable shared and replay the values, use observable.pipe(shareReplay(1)).

If you want to have the subscriber functionality as well, you need to use the ReplaySubject subscribed to the original Observable observable.subscribe(subject);.

like image 5
Dmitriy Kachko Avatar answered Oct 21 '22 10:10

Dmitriy Kachko