取(1)与FirstValue,从可观察到的Value。
在我的项目中,我使用cimakiorSubject
作为数据存储来存储我的应用程序的状态。
我只需要当前值,该值当前在evaryubjectubject
存储中,并且不需要订阅可以通过行为主题发出的未来值。
我发现如何做到这一点的实现很少:使用管道(拿(1))
,firstValuefrom
和.value
。
所有人都以相同的方式工作并阅读行为主题存储中的当前值吗? 它们之间有什么区别(如果有)?
private myStore$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
// reading only one current value using take(1):
this.myStore$.pipe(take(1))
.subscribe(value => console.log('current value = ', value));
// reading only one current value using firstValueFrom:
const value = await firstValueFrom(this.myStore$);
console.log('current value = ', value);
// reading only one current value using this.myStore$.value:
const value = this.myStore$.value;
console.log('current value = ', value);
In my project, I use BehaviorSubject
s as data stores to store the state of my application.
I need only the current value that is currently held in the BehaviorSubject
store, and don't need to subscribe to future values that can be emitted through the behavior subject.
I found few implementations of how to do this: using pipe(take(1))
, firstValueFrom
and .value
.
Do all work the same way and read the current value in the BehaviorSubject store?
What are the differences between them, if any?
private myStore$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
// reading only one current value using take(1):
this.myStore$.pipe(take(1))
.subscribe(value => console.log('current value = ', value));
// reading only one current value using firstValueFrom:
const value = await firstValueFrom(this.myStore$);
console.log('current value = ', value);
// reading only one current value using this.myStore$.value:
const value = this.myStore$.value;
console.log('current value = ', value);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基本上使用
take(1)
或firstValueFrom
是相同的,因为它们异步访问值:firstValueFrom
将 Observable 转换为 Promise,因此您可以使用 < code>async/await
:使用
BehaviorSubject.value
同步访问其值一般是不推荐。如果BehaviorSubject
错误或取消订阅,它可能会出现意外行为:实时演示:https://stackblitz.com/edit/rxjs-npalak?devtoolsheight=60
Basically using
take(1)
orfirstValueFrom
is the same because they access the value asynchronously:firstValueFrom
turns Observable into a Promise so you can useasync
/await
:Using
BehaviorSubject.value
to synchronously access its value is in general not recommended. It might behave unexpectedly ifBehaviorSubject
errors or when it's unsubscribed:Live demo: https://stackblitz.com/edit/rxjs-npalak?devtoolsheight=60