Rxjs Observable.take(1) vs Subscription.unsubscribe()
之间有什么区别
1 | Observable.pipe(take(1)).subscribe(...) |
与
1 2 3 4 | const subscription = Observable.subscribe(() => { // Do something, then subscription.unsubscribe() }) |
与
第三项是与rxjs相关的项目,其他与编码样式有关。
在这里看看示例。
在Angular2中,我发现自己同时使用了两种范例。
第一种方法在方法内部最有意义,第二种方法最好在构造函数中使用,而在解构函数中进行清理。
1 2 3 4 5 6 | doThing(){ this.store.select('thing').pipe(take(1)) .subscribe(item => { otherMethod(item) }); } |
与
1 2 3 4 5 6 7 8 9 10 11 12 13 | class SomeClass{ public val; private sub; constructor(){ this.sub = this.store.select('thing') .subscribe(item => { this.val = item }); } ngDestroy() { this.sub.unsubscribe() } } |