Search code examples
javarx-javarx-java2

How can I recheck every 1 second using RxJava?


Is there any method in RxJava to recheck if the variable is null or not, For example, Recheck every 1 second or when the value is given to the variable?

String x;

Completable.create(emitter -> {
    if (x != null)
        emitter.onComplete();
}).timeout(10, TimeUnit.SECONDS).subscribe();

Solution

  • Yes, start an interval and read the value of the variable in some other operator. Note though that you'll need a volatile variable to be safe:

    volatile String x;
    
    Observable.interval(1, TimeUnit.SECONDS)
    .takeUntil(t -> x != null)
    .ignoreElements()
    .subscribe(() -> System.out.println("Done!"));
    
    Observable.timer(3500, TimeUnit.MILLISECONDS)
    .subscribe(t -> { x = "value"; });