Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
CountDownTimer suing RXJava 2
import java.util.concurrent.TimeUnit;
import io.reactivex.Observer;
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.range(0, startValue.intValue()), io.reactivex.Observable.interval(1, timeUnit), (integer, aLong) -> {
Long l = startValue-integer;
return l;
.subscribe(new Observer<Long>() {
public void onSubscribe(Disposable d) {
disposable = d;
public void onNext(Long aLong) {
public void onError(Throwable e) {
public void onComplete() {
public void cancel(){
if(disposable!=null) disposable.dispose();
public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) {
new CountDownTimer(10L, TimeUnit.SECONDS) {
public void onTick(long tickValue) {
Log.d("CountDown", "Remaining: " + tickValue);
public void onFinish() {
Log.d("CountDown", "The End!! ");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.