RxJava Interval Operator

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
RxJava Interval Operator

I am Amit Shekhar, a mentor helping developers in getting high-paying tech jobs.

In this blog, we will learn about the Interval Operator of RxJava.

RxJava has operators for every use case. One of the very useful operators of RxJava is Interval Operator.

What is Interval Operator?

Interval Operator creates an Observable that emits a sequence of integers spaced by a given time interval.

We use the Interval operator when we want to do a task again and again after some interval.

The best way to understand is by taking an example. Let's take an example to understand the Interval Operator.

val disposable =
    Observable.interval(0, 2, TimeUnit.SECONDS)
        .flatMap {
            return@flatMap Observable.create<String> { emitter ->
                emitter.onNext("Amit Shekhar")
                emitter.onComplete()
            }
        }
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe {
            println(it)
        }

compositeDisposable.add(disposable)

Let's understand the parameters of the interval(long initialDelay, long period, TimeUnit unit):

  • initialDelay: the initial delay time to wait before emitting the first value
  • period: the period of time between emissions of the subsequent numbers
  • unit: the time unit for both initialDelay and period

So, in our example, it will start immediately as the provided initialDelay is 0, then, the task will be done again and again after 2 seconds of interval.

It will keep on printing the following forever:

Amit Shekhar
Amit Shekhar
Amit Shekhar
Amit Shekhar
Amit Shekhar
Amit Shekhar
Amit Shekhar
Amit Shekhar
...

As it will keep going on forever, there must be a way to stop it.

There are two ways to stop which are as follows:

  • Using the compositeDisposable.dispose()
  • Using the take(n) operator as below
Observable.interval(0, 2, TimeUnit.SECONDS)
    .take(5)
    .flatMap {
        return@flatMap Observable.create<String> { emitter ->
            emitter.onNext("Amit Shekhar")
            emitter.onComplete()
        }
    }
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe {
        println(it)
    }

Here, we have passed 5 as a parameter to the take() operator. It means that the task will be done only 5 times.

This will print the following:

Amit Shekhar
Amit Shekhar
Amit Shekhar
Amit Shekhar
Amit Shekhar

We must keep in mind that the Interval Operator runs on the Schedulers.computation(). So, we do not have to worry about the Schedulers.

Use case of Interval Operator: To do the task again and again with a particular time interval.

This way we can use RxJava Interval Operator to solve any problem in a very simple way.

Master Kotlin Coroutines from here: Mastering Kotlin Coroutines

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.