How to convert an Observable to a ReplaySubject in RxJS?

笑着哭i 提交于 2019-12-03 17:35:08

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/41730542/how-to-convert-an-observable-to-a-replaysubject-in-rxjs

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