Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava Observable that emits latest value upon subscription

I am building an Android MVVM application using RxJava2. What I want is to expose an Observable in my ViewModel, which I also can receive the last emitted value (like a BehaviourSubject). I don't want to expose a BehaviourSubject because I don't want the View to be able to call onNext().

For example, in my ViewModel I expose a date. I now want to subscribe a TextView to changes, but I also need to be able to access the current value if I want to show a DatePickerDialog with this date as initial value.

What would be the best way to achieve this?

like image 845
Simon Schiller Avatar asked Sep 20 '25 05:09

Simon Schiller


1 Answers

Delegate:

class TimeSource {
    final BehaviorSubject<Long> lastTime = BehaviorSubject.createDefault(
        System.currentTimeMillis());

    public Observable<Long> timeAsObservable() {
        return lastTime;
    }

    public Long getLastTime() {
        return lastTime.getValue();
    }

    /** internal only */
    void updateTime(Long newTime) {
        lastTime.onNext(newTime);
    }
}
like image 198
akarnokd Avatar answered Sep 21 '25 21:09

akarnokd