0

我对 RxJS 世界还很陌生(请原谅我的语义),但是我已经看到了一些代码示例,它们创建了一个 Subject 来做一些工作,然后调用 next(0) 或 next('r' ) 关于订阅。它似乎重新运行流,或者更确切地说从流中获取下一个值。

但是,当我尝试使用它为某些数据调用 API 时,它完全跳过了它应该按照流中定义的方式执行的工作(假设它会再次“运行”流并从服务器获取新数据),并且相反,当我尝试像这样调用 next 时,我的订阅者会返回 'r' 或零值。

我知道订阅“开始执行流”,可以这么说,但如果我想“重新运行”它,我必须取消订阅,每次都重新订阅。

用看似多余的值调用 next 是否是某种约定?我只是以错误的方式使用它,还是有一个像这样调用 next 的好用例?我确信我缺少一些基本的东西,或者我对它的工作原理的理解是非常错误的。

4

1 回答 1

1

这是一个很好的问题,我绝对建议您阅读有关冷热Observables的内容。

  • 每次有人访问它时,都会执行subscribeObservables 。
const a$ = of(5).pipe(tap(console.log))

a$.subscribe(); // the 'tap' will be executed here
a$.subscribe(); // and here, again.
  • hot Observables 在执行方面不关心订阅:
const a$ = of(5).pipe(
  tap(console.log),
  shareReplay(1)
);

a$.subscribe(); // the 'tap' will be executed here
a$.subscribe(); // but not here! console.logs only once

在您的示例中,您使用Subject的是代表的Observable。您可以尝试使用BehaviorSubjector ReplaySubject- 它们都很,但请注意它们的行为不同。

在您的示例中,您可以修改Subject如下:

const mySubject = new Subject();

const myStream$ = mySubject.pipe(
  shareReplay(1)
);

myStream$.subscribe(x => console.log(x))

mySubject.next(1);
mySubject.next(2);
mySubject.next(3);

于 2019-10-16T15:28:03.090 回答