Rxjava: [Newbie] Observable.interval Tick till set time or till flag is set

Created on 29 May 2017  路  1Comment  路  Source: ReactiveX/RxJava

I need to wait for a condition or timeout. I came up with the following approach, but there are too many things happening. How can i compress it

import io.reactivex.Observable;
import java.util.concurrent.TimeUnit;
import io.reactivex.schedulers.Schedulers;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.ThreadLocalRandom;

public class Test{
  public static void main(String[] args)throws InterruptedException{
    AtomicBoolean toggle = new java.util.concurrent.atomic.AtomicBoolean(true);

     Observable.interval(0,50, TimeUnit.MILLISECONDS)
                .takeWhile(l->l<(20000/50))
                .takeWhile(l-> toggle.get())
                .observeOn(Schedulers.io())
                .map(l->{ return (l>ThreadLocalRandom.current().nextInt(5, 20 + 1))?true:false;})
                 // The above map will call a remote function to check for some condition
                .observeOn(Schedulers.computation())
                .filter(exist->exist)
                //.takeWhile(exist->!exist)
                .map(l->{toggle.set(false);return l;})
                .map(l->{System.out.println("Called at "+l);return l;})
                .blockingSubscribe();
  }
}
2.x Question

Most helpful comment

Here are a couple of hints:

  • Combine the logical expressions of the two takeWhile.
  • The comparison against the random number already yields a boolean value, you don't need the ?:.
  • Use doOnNext to have side-effects instead of map and combine the two into a single lambda expression.
  • You may want to replace filter with takeUntil and you no longer need the toggle field as the sequence can stop after the first true received.

>All comments

Here are a couple of hints:

  • Combine the logical expressions of the two takeWhile.
  • The comparison against the random number already yields a boolean value, you don't need the ?:.
  • Use doOnNext to have side-effects instead of map and combine the two into a single lambda expression.
  • You may want to replace filter with takeUntil and you no longer need the toggle field as the sequence can stop after the first true received.
Was this page helpful?
0 / 5 - 0 ratings

Related issues

dsvoronin picture dsvoronin  路  4Comments

theblang picture theblang  路  3Comments

ZakTaccardi picture ZakTaccardi  路  3Comments

nltran picture nltran  路  4Comments

Jaap-van-Hengstum picture Jaap-van-Hengstum  路  3Comments