In the pass, to build the timer task, for example: to show count down timer on TextView or show current position when play the music or video use MediaPlayer, I use TimerTask or Timer object as the best choices.
This is the old source code
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (isTrue()) {
tv.post(new Runnable() {
@Override
public void run() {
tv.setText(getTimerText());
}
});
}
}
});
}
}, 0, 1000);
**Above solution is rarely basically, It's not good in some cases. **
int mSickTimer = 0;
//build the Observable object
final Observable<Integer> timerObservable = Observable.create(new Observable.OnSubscribe<Integer>() {
@Override
public void call(Subscriber<? super Integer> subscriber) {
subscriber.onStart();
while (isTrue()) {
subscriber.onNext(mSickTimer ++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
subscriber.onCompleted();
}
}
subscriber.onCompleted();
}
});
//Excute the observable by call *subscribe*,
// Key features here, you can control what thread excute timer and handle callback.
timerObservable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(timerObserver);
//timerObserver
timerObserver = new Observer<Integer>() {
@Override
public void onCompleted() {
//complete timer
}
@Override
public void onError(Throwable e) {
//error -> I will make it finish here
}
@Override
public void onNext(Integer i) {
updateTimer(i);
}
}
If you're interested with RxJava, you can try and give me your opinion.
Thanks!
this makes thread to sleep i guess