Android RxJava, how to start, stop, reset Observable.interval programmatically on run time!
In this sample app, we are creating a class that is triggering an event each n time, in addition we have added useful methods to the class, that will allow as to use it smoothly.
- setPeriod(int period): this method set the ticks period in seconds.
- start(): this mithod to start the observable.interval forever.
- stop(): to stop the observable.interval.
- setOnTickListener(OnTickListener onTickListener): listener method that will be called in heach tick.
to understand this samble, you should have a knowledge of:
- Java programming and Android.
- Java 8 lambda expressions.
- have a good knowledge of using Butterknife library.
This is a Samble app that is connecting to Nasa rest API service to get data and display it in a list view. This App aims to present of how to build a clean code using Dagger 2 and MVP structure.
This app has been designed in such a way to describe how to use the reactive programming (Observable.interval) using RxJava and butterknife.
subscription = Observable.interval(period, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(aLong -> {
onTickListener.onTick();
});
As you see, Observable.interval takes two parameters
- Period: the period between each tick
- Unit time and this code be in MILLISECONDS, SECONDS, DAYS, HOURS, MICROSECONDS, NANOSECONDS, and MINUTS.
Take care the ObserveOn will not run on UI thread if you did not pass AndroidSchedulers.mainThread
observeOn(AndroidSchedulers.mainThread())
and on each tick, the observer will call:
subscribe(aLong -> { //do what ever you want here... });
if (subscription != null && !subscription.isDisposed()) {
subscription.dispose();
}
- RxJava2: https://github.com/amitshekhariitbhu/RxJava2-Android-Samples
- ButterKnife: http://jakewharton.github.io/butterknife/
- Lambda: https://guides.codepath.com/android/Lambda-Expressions
- RxJava + Fast Android Networking
- Migrating from RxJava 1.0 to RxJava 2.0 and Learn RxJava by Examples
- RxJava Anatomy: What is RxJava, how RxJava is designed, and how RxJava works.
Check out amjadomari awesome open source projects here
Just make pull request. You are in!