since i would like to start my new app with a clean base im looking for a good way sharing Informations around different classes. For an example i would like to subscribe to an interface which may be used/shared by different classes.
Example for the interface/Observable way:
class SingleTonHolder {
private static _instance = null; // and initalize it using a static method.
private List<MyListener> myListeners new ArrayList<>();
public SingleTonHolder getInstance(){ return _instance }
public void registerListener(MyListener listener) { myListeners.add(listener); }
public void removeListener(MyListener listener) { myListeners.remove(listener); }
public void doSomethingToTheListener(...) { for(MyListener l : myListeners) l.doSomethingToTheListener(..); }
}
ClassOne extends MyListener {
public void onCreate() {
SingleTonHolder.getInstance().registerListener(this);
}
public vond onDestroy() {
SingleTonHolder.getInstance().removeListener(this);
}
}
and another class to listen for changes.
ClassTwo {
MyListener listener = null;
public void onCreate() {
listener = new MyListener( () => { .... });
SingleTonHolder.getInstance().registerListener(listener);
}
public vond onDestroy() {
SingleTonHolder.getInstance().removeListener(listener);
}
}
This does work and looks like the default solution. Everytime another Object calls SingleTonHolder.doSomethingToTheListener() it notify all registered listeners for changes.
Since i would like to try the same solution using RxJava2 and RxAndroid2 which lacks documentation i have tried the following way doing it.
Class CallFactory{
public Obvservable<List<Data>> getDummyData() { return anDummyObservable; }
}
Then ive created a Singleton Class which has a function to modify/observ onec a client subscribes.
public Observable<List<Data>> getData() {
return CallFactory.with(context)
.getDummyData(...)
.map(modifyList -> { /** do some processing **/return modifyList;
})
}
which doesnt work as excepted since every time a client subscribes it "recall" it and the client keeps connected until onCompleted() is called.
My first try to share the informations to all subscribed clients ive created a PublishSubject in my Singleton Class.
private PublishSubject<List<Data>> sharedSubject = PublishSubject.create();
Now i let my clients subscribe to the subjects using a method like
public PublishSubject getSharedSubject() { return this.sharedSubject; }
If i would like to send a Message which should be received by all listening clients then i have created something like
public void setNewData(List<Data> data) {
sharedSubject.onNext(data);
}
I am pretty sure that is not the way it should be, but is rxjava designed to serve such a solution? If i want to share events different then onNext, onError, onComplete, do i need to wrap an Interface in the onNext?
The codes are not tested and just to show how i understood it. Any help would be appreciate.
>` and all of them can observer the PublishSubject
– Budius Feb 20 '17 at 21:16