Use scheduling with RxAndroid

I am using RxAndroid observable to retrieve some object (String in this case). My service looks like this:

  public Observable<String> getRandomString() { return Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { //code to retrieve result subscriber.onNext("this is a string"); subscriber.onCompleted(); } }); } 

I subscribe to my presenter and post the result:

 public void loadRandomString() { Observable<String> observable = mService.getRandomString(); observable .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.newThread()) .subscribe(new Subscriber<String>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { mMainView.onError(e.getLocalizedMessage()); } @Override public void onNext(String string) { //do something with string } }); } 

This works fine and that’s it, but I want this operation to be periodic (every x minutes). I could use Timer or ScheduledThreadPoolExecutor to do this over and over, but I would like to see if there is any solution in the RxAndroid area. I have found some old solutions since 2013, but many of them are out of date now. Is this possible using some kind of recursion, or can I achieve this in a more elegant way?

Thanks in advance!

+5
source share
1 answer

What you probably want is Observable.interval() . It emits a time interval. You can then compose this into your Observable<String> , for example:

 Observable.interval(3, TimeUnit.MINUTES) .flatMap(new Func1<Long, Observable<String>>() { @Override public Observable<String> call(Long ignore) { return getRandomString(); } }) .subscribe(...insert your subscriber here...); 

However, if you intend to do this every few minutes, you might be better off looking in AlarmManager or JobScheduler , as it is likely that users will not be focused on your application for a long period of time.


As an aside, it would be much easier to use Observable.just("this is a string") than Observable.create() .

+6
source

Source: https://habr.com/ru/post/1238294/


All Articles