Created
May 11, 2017 07:00
-
-
Save paramsen/73bbfb65291a638dfc17c4498bf4dabd to your computer and use it in GitHub Desktop.
RxJava Timer for fun
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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