How to get latest value from BehaviorSubject?
Asked Answered
N

2

7

How can I retrieve the latest value from BehaviorSubject on RxAndroid?

Some background info: I'm using RxJava to implement MVVM pattern. My ViewModel encapsulates "bindable properties" that are BehaviorSubjects. I'm binding them to UI elements as observables, ensuring that the interface gets constantly updated (and thanks to using BehaviorSubject, it's going to happen even if the subscription takes place after setting the value).

I would still like to be able to access the latest (the actual) "raw" value of the property, for business logic.

How do I do that?

Surely BehaviorSubject caches it somehow, given that it republishes the latest value for whoever subscribes to it.

And yet BehaviorSubject.last() only returns an Observable<T>, and it doesn't seem to expose any methods of T return type.

I know I could cache it myself, but it feels redundant.

I guess I could also create a throw-away subscription in my getter, only to obtain the latest value with it and then return it to the calling code, but this seems clunky.

Is there anything neater on hand?

Necropolis answered 6/6, 2015 at 18:44 Comment(4)
Look at hasValue and getValue methods on the subject itself.Zalea
Well, that's about the first thing I was looking for ;) Unfortunately, it doesn't expose such methods, hence the question.Necropolis
RxJava has these methods since 1.0.6:reactivex.io/RxJava/javadoc/rx/subjects/…Zalea
@Zalea RxAndroid seems to be based on RxJava 1.0.4.Necropolis
N
3

As it turns out, the reason behind it is that RxAndroid by default depends on RxJava 1.0.4, where Subjects didn't expose getValue nor hasValue yet.

Thanks to @akarnokd for helping me realize that.

As it turns out, all it takes to resolve the problem is to manually add a dependency on latest version of RxJava side-by-side with RxAndroid dependency in build.gradle. As of now that would be:

compile 'io.reactivex:rxandroid:0.24.0'
compile 'io.reactivex:rxjava:1.0.11'

See https://github.com/ReactiveX/RxAndroid/issues/171

Necropolis answered 7/6, 2015 at 20:8 Comment(0)
A
0

It would be helpful if you use blockingGet()

subject.onNext(subject.blockingLast(null))
Arias answered 23/4, 2019 at 10:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.