【问题标题】:Observables: How does first behave whith other operators?Observables:首先如何处理其他操作符?
【发布时间】:2018-12-21 13:43:00
【问题描述】:

我一直在寻找答案,但找不到任何结论。 当我在 observable 上使用 first 运算符然后将其他运算符像 swtichMapmap 一样通过管道传递时会发生什么。

据我所知,当我使用 first 然后订阅它时,它会一直存在,直到返回第一个值:

myObs.first().subscribe(console.log);
// I shouldn't be worried about unsiscribe
myObs.pipe(first()).subscibe(console.log);
// The same here

但是当我管道其他函数时会发生什么,我将问题分为两点,首先,当我使用简单运算符(不返回其他 observable 的运算符)时会发生什么:

// 1. Will this subscription end on first emitted value?
myObs.first().pipe(map(data => return data.content)).subscribe(console.log);

// 2. Is this different from (1)
myObs.pipe(first(), map(data => return data.content)).subscribe(console.log);

// 3. Will this subscription end on first emitted value?
myObs.pipe(map(data => return data.content), first()).subscribe(console.log);

我认为会发生什么:

  • (1) 和 (2) 相同,如果我们不取消订阅,订阅将永远有效,但它只会发出一个值。内部订阅将结束,但外部订阅不会。
  • (3) 与 (1,2) 相反,内部订阅将永远存在,外部订阅将在第一次发出值后结束。有内订阅吗?还是我错了?

最后,使用switchMap() 会有什么改变吗?如果我们使用switchMap() 而不是flatMap(),它将以每个新值结束内部订阅,但是上面的问题会发生什么?

编辑:我们是否应该使用first() 作为管道的开头并最终确保订阅将结束?

// 3. Has these any sense?
myObs.pipe(frist(), map(data => return data.content), first()).subscribe(console.log);

【问题讨论】:

  • 我看起来你想在任何地方使用 flatMap 而不是 map()

标签: rxjs observable angular2-observables


【解决方案1】:

如果您在 first() 之后使用 switchMapconcatMapmergeMap (flatMap),则可能会导致多个事件取决于您的代码,因此请检查您的代码是否生成事件。常规map 无法引发新事件。

// this stream emits event every second.
stream$.pipe(
  first(),
  mergeMap(() => interval(1000)
);

无需将first 放在开头和结尾。如果您知道您没有流中的流,请将其放在开头(不要像运算符一样调用mergeMap)。在其他情况下放在最后first

【讨论】:

  • 我知道map 我不会收到任何新事件,但我问的是自动退订。想象一下,我的流将始终只返回一个值,2 订阅点会在第一次发出值后完成吗?我觉得不会
  • @Gonzo,我相信,你不需要取消订阅以防万一2。这是关于 medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87 的热门帖子
猜你喜欢
  • 2016-05-30
  • 1970-01-01
  • 1970-01-01
  • 2014-03-25
  • 2018-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多