I was wondering what the main difference is between the getValue
function and the readonly value
property on the BehaviorSubject
? Is there a benefit of using one over the the other?
So the only solution that I found to get the value of a BehaviorSubject was: let value; myBehaviorSubject. take(1). subscribe( (e) => value = e );
BehaviorSubject is both observer and type of observable. BehaviorSubject always need an initial/default value. Every observer on subscribe gets current value. Current value is either latest value emitted by source observable using next() method or initial/default value.
The BehaviorSubject There are two ways to get this last emited value. You can either get the value by accessing the . value property on the BehaviorSubject or you can subscribe to it. If you subscribe to it, the BehaviorSubject will directly emit the current value to the subscriber.
BehaviorSubject is a variant of a Subject which has a notion of the current value that it stores and emits to all new subscriptions. This current value is either the item most recently emitted by the source observable or a seed/default value if none has yet been emitted.
There is no difference between the two methods.
Internally the BehaviorSubject
returns the value from getValue()
. So if you are super picky about performance, then calling getValue()
saves you one function call.
get value(): T {
return this.getValue();
}
https://github.com/ReactiveX/rxjs/blob/1d29fe8b903c0dbc2b74a5e68abb9270e3f45015/src/internal/BehaviorSubject.ts#L19
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With