Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to get the current value of a BehaviorSubject with rxjs5

Previously in rxjs4 there was a method in the BehaviorSubject called: getValue() (doc here).

This method does not exist anymore in rxjs5.

So the only solution that I found to get the value of a BehaviorSubject was:

let value;
myBehaviorSubject.take(1).subscribe( (e) => value = e );

This code runs synchronously (I do not exactly understand why, but it does ...) and gets the value. It works, but it's not as clean as it could be if getValue() was present:

let value = myBehaviorSubject.getValue();

Why getValue() was removed in rxjs5 and what's the cleanest solution to this problem?

like image 833
Clement Avatar asked Aug 05 '16 08:08

Clement


People also ask

How do I find the current value in BehaviorSubject?

If you want to have a current value, use BehaviorSubject which is designed for exactly that purpose. BehaviorSubject keeps the last emitted value and emits it immediately to new subscribers. It also has a method getValue() to get the current value.

How do you find the current value of an Observable?

To get current value of RxJS Subject or Observable, we can use the first method. const observable = of("foo"); const hasValue = (value: any) => { return value !== null && value !== undefined; }; const getValue = <T>(observable: Observable<T>): Promise<T> => { return observable.

How do I get last emitted value from BehaviorSubject?

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.

How do I get my ReplaySubject value?

subscribe(num => console. log('last: ' + num)); If you don't want your stream to end, but you do want subscribers to receive the last value emitted before subscription, consider reaching for BehaviorSubject , which was designed for this use case.


2 Answers

As was pointed out by artur grzesiak in the comments, the BehaviorSubject interface was cleaned up, and the getter is now just myBehaviorSubject.value.

I just wanted to add this as an answer because I almost didn't read the comments to the original question, and would have missed the correct answer.

like image 108
Tyson Phalp Avatar answered Oct 09 '22 08:10

Tyson Phalp


Look at the source code to a behavior subject

https://github.com/ReactiveX/rxjs/blob/master/src/internal/BehaviorSubject.ts

It still has a getValue method, it has a value property that just calls getValue, it was there in RxJs5.

Here is a StackBlitz using RxJs5.

https://stackblitz.com/edit/typescript-gcbif4

All the comments talking about a breaking change in 6.5.0 are linking to comments about observables make with of not behavior subjects.

like image 7
Adrian Brand Avatar answered Oct 09 '22 07:10

Adrian Brand