Reputation: 164129
I'm trying to jump on the reactive bandwagon, but after reading and going through lots of examples, I still haven't found what I'm looking for.
I have a model object which might get change during any time in the lifecycle of the application.
The changes might come from a specific request to update it (from servers, db, etc) or it might get updated due an event which fires in the app.
My question is how do I create an Observable
of such an object and how do I keep updating the subscribers when there's a change?
From what I've seen so far I can create the observable like so:
Observable.create(new Observable.OnSubscribe<MyModel>() {
@Override
public void call(final Subscriber<? super MyModel> subscriber) {
subscriber.onNext(MyModel instance);
}
});
What I'm missing here:
I do not want to emit different values (instances of MyModel
) but just want to let the subscribers know that the same instance (the one on which they subscribed on) has changed.
If I understand it right, then the call
method is invoked whenever a new subscriber has registered, but that's not what I need, I need to take action only when there's an update and then I want to notify ALL subscribers.
There's a good chance that I just got this all wrong, which is why I'd be happy to understand how it's possible to accomplish my needs with RxJava.
Thanks.
Upvotes: 11
Views: 5244
Reputation: 9569
I think the best option to do stuff like that is Subjects. So you can have something like this:
public static class MyModel {
private PublishSubject<MyModel> changeObservable = PublishSubject.create();
private String field1;
public String getField1() {
return field1;
}
public void setField1(String field1) {
this.field1 = field1;
changeObservable.onNext(this);
}
public Observable<MyModel> getModelChanges() {
return changeObservable;
}
@Override
public String toString() {
return "MyModel{" +
"field1='" + field1 + '\'' +
'}';
}
}
public static void main(String[] args) {
MyModel myModel = new MyModel();
myModel.getModelChanges()
.subscribe(System.out::println);
myModel.setField1("1");
myModel.setField1("2");
myModel.setField1("3");
}
So all setters in the model will notify that something has changed in your model and all subscribers will get that data.
Upvotes: 20