假设我有以下代码
Injectable()
export class MyStore {
store = new BehaviorSubject(true);
updateStore(value) {
this.store.next(value);
return this.store.asObservable();
}
selectValue() {
return this.store.asObservable();
}
}
是否有可能从 updateStore 返回的可观察量没有 next(( 更新的值?上面的代码有什么陷阱吗?
是否有可能从 updateStore 返回的可观察量没有 next(( 更新的值?
不,可观察将始终具有在 next()
中传递的值。话虽如此,每当订阅在返回值 updateStore()
上完成时,订阅者将收到在 next()
中传递的值。
上面的代码有什么陷阱吗?
你不需要每次做"下一个"时都return this.store.asObservable()
。消费者(即订阅者(只需订阅 MyStore.store 因为"商店"本身就是一个可观察的。
updateStore(value) {
this.store.next(value);
}
是否有可能从 updateStore 返回的可观察量没有 next(( 更新的值?
这不可能。BehaviorSubject 是同步的,因此该值是在调用 next()
返回之前设置的。
https://github.com/ReactiveX/rxjs/blob/master/src/internal/BehaviorSubject.ts#L42
next(value: T): void {
super.next(this._value = value);
}
上面的代码有什么陷阱吗?
从updateStore()
返回可观察量是没有意义的。函数的调用方已经知道存储的值。设置值没有延迟,因此调用方无需等待结果。
其他一切看起来都很好。