Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rxjava delay: How to get variable delay on each item emitted from a list?

Tags:

java

rx-java

I want to have custom delays between each item emitted from an observable list as a function of the items themselves. Let's say we have a list as (item, delay):

[("item1", 2),("item2", 1),("item3", 2),("item4", 3),("item5", 2),("item6", 3)]

I want output to be something like:

0 seconds: 
1 seconds: 
item1
2 seconds: 
item2
3 seconds: 
4 seconds: 
item3
5 seconds: 
6 seconds: 
7 seconds: 
item4
8 seconds: 
9 seconds: 
item5
10 seconds: 
11 seconds: 
12 seconds: 
item6
Completed!
13 seconds: 

I am not sure how to best accomplish this with delay/timer operators. Went through delay documentation but couldn't figure out a straightforward way. Any pointers would be helpful. Thanks!

like image 849
abhimskywalker Avatar asked Aug 18 '16 07:08

abhimskywalker


2 Answers

No need for anything fancy. Just use concatMap and delay operators

jla.concatMap(s -> Observable.just(s).delay(s.delay, TimeUnit.SECONDS))           
  .subscribe(s1 -> System.out.println(s1.name + " just came..."), 
             e -> {}, 
             () -> System.out.println("Everybody came!")); 
like image 156
JohnWowUs Avatar answered Nov 09 '22 23:11

JohnWowUs


You may try to use this override of .delay() http://reactivex.io/RxJava/javadoc/rx/Observable.html#delay(rx.functions.Func1)

It seems exactly what you need

The code would be something like:

yourObservable.delay((item) -> Observable.timer(item.getDelay(), TimeUnit.SECONDS))
like image 36
CristianGM Avatar answered Nov 09 '22 22:11

CristianGM