Steven Schoen
Steven Schoen

Reputation: 4386

Giving an RxJava Observable something to emit from another method

I have a variable in a Fragment that will have its value change multiple times throughout the Fragment's life. It's triggered by UI interactions, so I thought it might be a good idea to use an Observable to hold it, rather than make all of the to-be-updated views as fields and do my UI changes from a setter.

The value has to be updated through another method (basically a setter that should call onNext() on the subscriber), not through the Observable itself. Is there a way to do that with RxJava's design?

In other words, I'm looking to have an Observable field, and give it new values to emit (calling onNext() on its subscribers) from another method in the class.

Upvotes: 13

Views: 4375

Answers (1)

Vladimir Mironov
Vladimir Mironov

Reputation: 30874

RxJava has Subjects for this purpose. For example:

private final PublishSubject<String> subject = PublishSubject.create();

public Observable<String> getUiElementAsObservable() {
    return subject;
}

public void updateUiElementValue(final String value) {
    subject.onNext(value);
}

Upvotes: 21

Related Questions