Skip to content

Instantly share code, notes, and snippets.

@chemickypes
Created April 27, 2017 12:51
Show Gist options
  • Save chemickypes/fa3b7fc5b5a00a3ce37fee5815018702 to your computer and use it in GitHub Desktop.
Save chemickypes/fa3b7fc5b5a00a3ce37fee5815018702 to your computer and use it in GitHub Desktop.
CountDownTimer suing RXJava 2
import java.util.concurrent.TimeUnit;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
/**
* Created by Angelo Moroni on 27/04/17.
*/
public abstract class CountDownTimer {
private TimeUnit timeUnit;
private Long startValue;
private Disposable disposable;
public CountDownTimer(Long startValue,TimeUnit timeUnit) {
this.timeUnit = timeUnit;
this.startValue = startValue;
}
public abstract void onTick(long tickValue);
public abstract void onFinish();
public void start(){
io.reactivex.Observable.zip(
io.reactivex.Observable.range(0, startValue.intValue()), io.reactivex.Observable.interval(1, timeUnit), (integer, aLong) -> {
Long l = startValue-integer;
return l;
}
).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Long>() {
@Override
public void onSubscribe(Disposable d) {
disposable = d;
}
@Override
public void onNext(Long aLong) {
onTick(aLong);
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onComplete() {
onFinish();
}
});
}
public void cancel(){
if(disposable!=null) disposable.dispose();
}
}
public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_activity);
new CountDownTimer(10L, TimeUnit.SECONDS) {
@Override
public void onTick(long tickValue) {
Log.d("CountDown", "Remaining: " + tickValue);
}
@Override
public void onFinish() {
Log.d("CountDown", "The End!! ");
}
}.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment