Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RXJava how to try to get next after x time

I wan to do a call to a web service using retrofit every x seconds until y condition is raised.

I want to run OrderApi.get after x seconds until the response is null.

public class OrderApi {}
    public static Observable<Order> get() { 
        //...
    }
}


OrderApi.get(order.getId()))
        .subscribe(updatedOrder -> {
          mShouldRun = updatedOrder != null;
        });

Already saw operators like Observable.delay Observable.timber but I cant find a way to use them properly.

like image 295
Daniel Gomez Rico Avatar asked Oct 22 '15 18:10

Daniel Gomez Rico


2 Answers

this should work

 Observable.interval(1, TimeUnit.SECONDS)
                .flatMap(new Func1<Long, Observable<?>>() {
                    @Override
                    public Observable<?> call(Long aLong) {
                        return OrderApi.get();
                    }
                }).takeUntil(new Func1<Object, Boolean>() {
            @Override
            public Boolean call(Object o) {
                return o==null;
            }
        }).subscribe(observer);
like image 190
FriendlyMikhail Avatar answered Nov 17 '22 17:11

FriendlyMikhail


a combination of timer and repeat should do it

Observable.timer(1000, TimeUnit.MILLISECONDS)
       .subscribeOn(Schedulers.io())
       .observeOn(AndroidSchedulers.mainThread())
       .repeat(Schedulers.io())
       .subscribe(new Action1<Object>() {
           @Override
           public void call(Object aLong) {
              System.out.println(System.currentTimeMillis());
           }
       });

the callback call is called every 1 sec

like image 21
Blackbelt Avatar answered Nov 17 '22 16:11

Blackbelt