How to convert an Observable to a ReplaySubject?

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


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

Tags:

Rxjs

Rxjs5