Reputation: 164147
I'm trying to create a proxy to my models using RxJava, this proxy lets other subscribe for changes in the model.
Here's a simplified version of my proxy:
class MyModelProxy {
private static MyModelProxy instance;
private MyModel model;
private PublishSubject<MyModel> subject;
private MyModelProxy() {
this.model = // load from cache
this.subject = PublishSubject.create();
}
public static Observable<MyModel> observe() {
if (instance == null) {
instance = new MyModelProxy();
}
return instance.subject;
}
private void modelUpdated() {
this.subject.onNext(this.model);
}
}
There's only one instance of MyModel
in the system, but it might change over time, and so I want to be able to register for these updates.
This code works well if I register on the Observable
returned from the observe
method before calling the onNext
of the subject.
The behavior I want is that when the subscribe
method is called on this observer then the current instance of MyModel
will be sent to the subscriber that just subscribed.
I thought about extending the PublishSubject
but it's final, so I thought about writing my own version of it (mostly by copying what's in PublishSubject
and adding what I need) but then I found out that SubjectSubscriptionManager
has package visibility so that's a dead end too.
Any ideas how I can add this needed functionality?
Thanks.
Upvotes: 0
Views: 416
Reputation: 1960
There is also BehaviorSubject
, which does exactly what you want: emits most recent and all future items to its subscribers
Upvotes: 1