Search code examples
javaandroidreactive-programmingrx-javarx-android

How to get latest value from BehaviorSubject?


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?


Solution

  • 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