Observable interval method

In this post under RxJava, I will explain with example how to use the static “interval” method of Observable class.

This static method generates a stream of numbers of data type long with a time gap between generation of numbers.

They are two overloaded versions of “interval” method, one that accepts an intial delay in unit of time and in case of another there will be no initial delay.

They are also other two overloaded version of “interval” method, which accepts Scheduler instance. I will cover this version of methods in future posts.

Below is an example of the overloaded version which doesn’t take an initial delay as parameter.

Example 1


1  import java.util.concurrent.TimeUnit;
2  
3  import io.reactivex.rxjava3.core.Observable;
4  
5  public class Example4_1 {
6      public static void main(String[] args) throws Exception {
7          Observable<Long> observable = Observable.interval(500, TimeUnit.MILLISECONDS);
8          observable.subscribe(i -> System.out.print(i + ","));
9          Thread.sleep(6000);
10     }
11 }

In the above code, at line 7, we are creating an Observable instance that generates numbers with a gap of 500 milliseconds between each generation.

At line 8, we subscribe to the Observable by calling the “subscribe” method, and passing the callback functionality as an argument to “subscribe” method. This callback function is called whenever an item is sent from the Observable. In our example this callback function simply prints the item sent.

The output will be

Output 1

0,1,2,3,4,5,6,7,8,9,10,11,

Below is an example of the second overloaded version which takes initial delay as parameter

Example 2


1  import java.util.concurrent.TimeUnit;
2  
3  import io.reactivex.rxjava3.core.Observable;
4  
5  public class Example4_2 {
6      public static void main(String[] args) throws Exception {
7          Observable<Long> observable = Observable.interval(2000, 500, TimeUnit.MILLISECONDS);
8          observable.subscribe(i -> System.out.print(i + ","));
9          Thread.sleep(6000);
10     }
11 }

In the above code, at line 7, we are creating an Observable instance that generates numbers with a gap of 500 milliseconds between each generation. There will be a
initial delay of 2 seconds. After 2 seconds the Observable will start generating numbers. Note the third argument which tells unit of time is used by both first and
second argument.

At line 8, we subscribe to the Observable by calling the “subscribe” method, and passing the callback functionality as an argument to “subscribe” method. This callback function is called whenever an item is sent from the Observable. In our example this callback function simply prints the item sent.

The output will be

Output 2

0,1,2,3,4,5,6,7,8,

The code in Example 2 is same as code in Example 1 with only one difference that is the use of initial delay in Example 2. As a result the output in Output 2 will print numbers till 8.

Leave a Reply