【发布时间】:2018-12-21 13:43:00
【问题描述】:
我一直在寻找答案,但找不到任何结论。
当我在 observable 上使用 first 运算符然后将其他运算符像 swtichMap 或 map 一样通过管道传递时会发生什么。
据我所知,当我使用 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