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

JavascriptReactive ProgrammingRxjsRxjs5Behaviorsubject

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionClementView Question on Stackoverflow
Solution 1 - JavascriptTyson PhalpView Answer on Stackoverflow
Solution 2 - JavascriptAdrian BrandView Answer on Stackoverflow