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();
}
}
Here are a couple of hints:
takeWhile.?:.doOnNext to have side-effects instead of map and combine the two into a single lambda expression.filter with takeUntil and you no longer need the toggle field as the sequence can stop after the first true received.
Most helpful comment
Here are a couple of hints:
takeWhile.?:.doOnNextto have side-effects instead ofmapand combine the two into a single lambda expression.filterwithtakeUntiland you no longer need thetogglefield as the sequence can stop after the firsttruereceived.