Skip to content

Instantly share code, notes, and snippets.

@paramsen
Created May 11, 2017 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paramsen/73bbfb65291a638dfc17c4498bf4dabd to your computer and use it in GitHub Desktop.
Save paramsen/73bbfb65291a638dfc17c4498bf4dabd to your computer and use it in GitHub Desktop.
RxJava Timer for fun
/**
* Rx based timer that implements a simple timer functionality. Should be
* disposed when it goes out of scope since RxJava leaks otherwise.
*
* @author Pär Amsen 05/2017
*/
public class Timer {
private Observable<Void> timer;
private long time;
private boolean started;
public Timer() {
timer = Observable.<Void>create(sub -> {
while (started && sub.isUnsubscribed()) {
time += 10;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
sub.onCompleted();
}).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread());
}
public void start() {
time = 0;
started = true;
timer.subscribe();
}
public void pause() {
started = false;
}
public void resume() {
started = true;
timer.subscribe();
}
public long stop() {
started = false;
return time;
}
public long getTime() {
return time;
}
public void dispose() {
started = false;
timer = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment