praj praj - 4 months ago 36
Android Question

Call web service with different time interval?

I am new in Rx android.i am trying to call web service in different time interval.

call Api 4 hours every 1 minutes for 30 minutes, then every 5 minutes for 3 hours and 30 minutes

is it possible to do with Rx android.if possible let me know how to do this?

Observable.interval(1,TimeUnit.MINUTES).takeWhile(Observable.timer(30,TimeUnit.MINUTES).concatWith(Observable.interval(5,TimeUnit.MINUTES).takeWhile(Observable.timer(30,TimeUnit.MINUTES).flatMap(new Func1<Long, Observable<?>>() {
@Override
public Observable<?> call(Long aLong) {
return null;
}
}).subscribe((new Observer<Object>() {
@Override
public void onCompleted() {
Log.e("working", "onCompleted");
}

@Override
public void onError(Throwable e) {
Log.e("working", "onComThrowablepleted");
}

@Override
public void onNext(Object o) {
Log.e("working", "onNext");

}
});
))

Answer

You can use interval, takeUntil, timer and concatWith : The idea is to use interval and stop it after 30 minutes, then use another interval.

 // 1 events per minutes
 Observable.interval(1, MINUTES)
           // and stop it after 30 minutes
           .takeUntil(Observable.timer(30, MINUTES))
           // then 1 events per 5 minutes, and stop it after 30 minutes
           .concatWith(Observable.interval(5, MINUTES).takeUntil(Observable.timer(30, MINUTES)))
           // perform webservice call
           .flatMap(time -> webservice.call())
           .subscribe();