简体   繁体   中英

Making a Rest api call at every x minutes using RxJava and Retrofit

I am currently working on making call to rest api and show data on UI. I am using rxAndroid and Retrofit. Following is the code :

disposable.add(apiService.getIncidents(1, "true")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Function<IncidentResponse, List<Incident>>() {
                    @Override
                    public List<Incident> apply(
                            @io.reactivex.annotations.NonNull final IncidentResponse incidentResponse)
                            throws Exception {
                        return incidentResponse.getIncidents();
                    }
                })
                .subscribe(new Consumer<List<Incident>>() {
                    @Override
                    public void accept(
                            @io.reactivex.annotations.NonNull final List<Incident> incidents)
                            throws Exception {
                        recyclerView.setAdapter(mIncidentAdapter);
                        displayIncidents(incidents);
                    }
                })
        ); 

This is working fine and I am able to fetch the data and show on UI. Now as part of enhancement , I need to fetch this data periodically even though my application is in background or killed. I tried the following code :

 disposable.add(((apiService.getIncidents(1, "true")).interval(10,TimeUnit.SECONDS))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Function<IncidentResponse, List<Incident>>() {
                    @Override
                    public List<Incident> apply(
                            @io.reactivex.annotations.NonNull final IncidentResponse incidentResponse)
                            throws Exception {
                        return incidentResponse.getIncidents();
                    }
                })
                .subscribe(new Consumer<List<Incident>>() {
                    @Override
                    public void accept(
                            @io.reactivex.annotations.NonNull final List<Incident> incidents)
                            throws Exception {
                        recyclerView.setAdapter(mIncidentAdapter);
                        displayIncidents(incidents);
                    }
                })
        );

But I am getting compilation error at method map that "in Observable cannot be applied". Is this the correct approach or this cannot be done using RxAndroid ?

The answer to your question is use JobScheduler or use a work Manager to run your task at a span of particular interval.

I personally suggest you to use work manager as you can schedule your task to run at a periodic interval even when the application is in background.

MyWorker.kt

class MyWorker(val ctx: Context, val params: WorkerParameters) 
: Worker(ctx, params) {

      override fun doWork(): Result {
         //Here you can run place your api call
        return Result.success()
    }

Activity.kt

 val workManager = WorkManager.getInstance()
        val myWork = PeriodicWorkRequest.Builder(MyWorker::class.java, 15, TimeUnit.MINUTES)
                .addTag(TAG)
                .setConstraints(constraints)
                .build()
        workManager.enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.KEEP, myWork)//starts work Manager

Here's a working sample This sample will a request every 5 seconds.Change that as necessary

        Observable.interval(1, 5, TimeUnit.SECONDS)
                .flatMap(new Function<Long, ObservableSource<List<ActivityGroup>>>() {
                    @Override
                    public ObservableSource<List<ActivityGroup>> apply(Long aLong) throws Exception {
                        return ServiceGenerator.createService(ActivityGroupAPI.class).getActivityGroup().subscribeOn(Schedulers.io());
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DisposableObserver<List<ActivityGroup>>() {
                    @Override
                    public void onNext(List<ActivityGroup> activityGroups) {
                        Calendar cal = Calendar.getInstance();
                        Timber.i("%s: %s", cal.getTime().toString(), activityGroups.size());
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });

Logcat

SettingsActivity: Wed Mar 27 16:42:25 GMT+05:45 2019: 2
SettingsActivity: Wed Mar 27 16:42:29 GMT+05:45 2019: 2
SettingsActivity: Wed Mar 27 16:42:34 GMT+05:45 2019: 2
SettingsActivity: Wed Mar 27 16:42:39 GMT+05:45 2019: 2
SettingsActivity: Wed Mar 27 16:42:44 GMT+05:45 2019: 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM