RxJava, RxAndroid sample
Source: Medium, danlew, Medium and Medium and GitHub, GitHub
Answer: Install RxAndroid, optional if you have to deal with Parse instal RxParse
Sample easy eaxmple to create a task that count the number of days ago:
CountDaysAgoTask.java
:public class CountDayAgoTask {
private Observable<String> mCountDayObservable;
public CountDayAgoTask(Date date){
setupObservable(date);
}
private void setupObservable(final Date date){
mCountDayObservable = Observable
.fromCallable(new Callable<String>() { //Callable only emit one value and only emit once there's a subscription to it
@Override
public String call() throws Exception {
return yourFunctionToCount(date);
}
});
}
public Observable<String> getCountDayObservable() {
return mCountDayObservable;
}
}
Then in whatever class or Activity
you need to receive the result:
public void setDaysAgoInBackground(final Date date) {
if (date != null) {
CountDayAgoTask countDayAgoTask = new CountDayAgoTask(date);
Observable<String> countDayObservable = countDayAgoTask.getCountDayObservable();
mCountDaySub = countDayObservable
.subscribeOn(Schedulers.io()) //these two line is to make the task run in a different thread
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<String>() { //this is where the subscription begin
@Override
public void onCompleted() {
if (mCountDaySub != null && !mCountDaySub.isUnsubscribed()) { //either do this here on your Activity's onStop
mCountDaySub.unsubscribe();
}
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(String s) {
yourTextView.setText(s);
}
});
}
}