As I do this, you need to have one-on-one class (or any long live object, as explained earlier with savepopulation, but the trick is to store the loaded data in a BehaviorSubject and subscribe to this object in Activity instead of the original network request .
Thus:
public class MyNetworkSingleton {
public static MyNetworkSingleton INSTANCE = new MyNetworkSingleton();
private final BehaviorSubject<String> dataSubject = BehaviorSubject.create();
public Observable<String> getData() {
if (!dataSubject.hasValue()) {
refreshData();
}
return dataSubject;
}
public void refreshData() {
someDataSourceCall().subscribe(new Observer<String>() {
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String data) {
dataSubject.onNext(data);
}
});
}
private Observable<String> someDataSourceCall() {
return
}
}
and then:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Observer<String> myObserver = new Observer<String>() {
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String s) {
Log.e("MY OBSERVER", s);
}
};
MyNetworkSingleton.INSTANCE.getData().subscribe(myObserver);
myRefreshButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
MyNetworkSingleton.INSTANCE.refreshData();
}
});
}
Thus, only for the first time you will need data from the network that will be downloaded or when the user clicks the update button ( myRefreshButton
).
source
share