RXJava how to try to get next after x time

纵饮孤独 提交于 2019-12-23 10:02:29

问题


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.


回答1:


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);



回答2:


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



来源:https://stackoverflow.com/questions/33288546/rxjava-how-to-try-to-get-next-after-x-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!