RxJava Observable with last state
Asked Answered
A

1

7

I’m starting with RxJava, and I would like to create an observable that can save the last state…

In RxSwift, that would be Variable (https://github.com/ReactiveX/RxSwift/blob/master/Documentation/GettingStarted.md#variables), but I can’t found an equivalente in RxJava…

I found a work around but it’s a lot of boiler plate code

private boolean isGettingCompanies = false;

public boolean isGettingCompanies() {
    return isGettingCompanies;
}

private void setIsGettingCompanies(boolean isGettingCompanies) {
    this.isGettingCompanies = isGettingCompanies;
    isGettingCompaniesPublishSubject.onNext(isGettingCompanies);
}

private final PublishSubject<Boolean> isGettingCompaniesPublishSubject = PublishSubject.create();

public Observable<Boolean> isGettingCompaniesPublishSubject() {
    return isGettingCompaniesPublishSubject.asObservable();
}

the RxSwift equivalent is this

private(set) var isGettingCompanies: Variable = Variable(false)

Can you help me please? Thanks

Altogether answered 7/4, 2016 at 9:57 Comment(0)
S
4

BehaviorSubject has a value() method which returns it's current value

final BehaviorSubject<Boolean> subject = BehaviorSubject.<Boolean>create(false);
final Boolean value = subject.getValue();
Shevat answered 7/4, 2016 at 13:22 Comment(2)
Thanks a lot, that was exactly what I was looking for :) If you allow me one more question. Is there any way of subscribe to this BehaviorSubject, receive his last value and the continue to receive the next events?Altogether
You could use the replay operator (with capacity set to 1).Pugliese

© 2022 - 2024 — McMap. All rights reserved.