假设我有以下代码
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()之前更新的值?上面的代码有什么缺陷吗?
发布于 2019-06-07 16:48:45
从updateStore返回的可观察到的值是否可能没有在next()之前更新的值?
不,“可观测”总是有next()中传递的值。话虽如此,每当对updateStore()的返回值执行订阅时,订户将接收在next()中传递的值。
上面的代码有什么缺陷吗?
您不必每次做“下一步”时都使用return this.store.asObservable()。用户(即订阅者)只需将MyStore.store订阅为“商店”,这本身就是可以观察到的。
updateStore(value) {
this.store.next(value);
}发布于 2019-06-07 16:46:55
从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()返回一个可以观察到的东西是毫无意义的。函数的调用方已经知道存储的值。在设置值方面没有任何延迟,因此调用方不需要等待结果。
其他一切看起来都很好。
https://stackoverflow.com/questions/56498274
复制相似问题