RxJava delay for each item of list emitted

RxJava delay for each item of list emitted

In RxJava, you can use the delay operator to introduce a delay between emitting each item in a list. To do this, you can convert your list into an observable and then apply the delay operator with a specified delay duration. Here's an example:

import io.reactivex.rxjava3.core.Observable; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; public class RxJavaDelayExample { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); Observable.fromIterable(numbers) .delay(1, TimeUnit.SECONDS) // Delay each item by 1 second .subscribe( item -> System.out.println("Received: " + item), Throwable::printStackTrace, () -> System.out.println("Done") ); // Sleep to keep the program running for a while to observe the delayed emissions try { Thread.sleep(6000); // Sleep for 6 seconds to observe all emissions } catch (InterruptedException e) { e.printStackTrace(); } } } 

In this example:

  1. We have a list of integers called numbers.

  2. We convert the list into an observable using Observable.fromIterable(numbers).

  3. We apply the delay operator with a delay of 1 second using delay(1, TimeUnit.SECONDS). This will introduce a 1-second delay between emitting each item.

  4. We subscribe to the observable, specifying three callbacks: one for each item received, one for handling errors, and one for the completion event.

  5. We add a Thread.sleep to keep the program running for a while so that we can observe the delayed emissions. During this time, you will see each item being emitted with a 1-second delay between them.

Make sure to include the RxJava library in your project dependencies to use RxJava operators like delay.


More Tags

crc16 factory-pattern curve-fitting schema fastlane executemany algorithms intellij-idea remote-connection appium

More Java Questions

More Mixtures and solutions Calculators

More Mortgage and Real Estate Calculators

More Biochemistry Calculators

More Organic chemistry Calculators