使用RxJava和Retrofit每隔x分钟进行一次REST API调用

时间:2019-02-28 14:11:57

标签: java android retrofit rx-java rx-android

我目前正在努力调用rest api并在UI上显示数据。我正在使用rxAndroid和Retrofit。以下是代码:

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

这工作正常,我能够获取数据并在UI上显示。现在,作为增强功能的一部分,即使我的应用程序处于后台或已终止运行,我也需要定期获取此数据。我尝试了以下代码:

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

但是我在方法映射上遇到“无法应用Observable中的”编译错误。这是正确的方法还是使用RxAndroid无法完成?

2 个答案:

答案 0 :(得分:0)

您的问题的答案是使用JobScheduler或使用工作管理器以特定间隔运行任务。

我个人建议您使用工作管理器,因为即使您的应用程序处于后台,您也可以安排任务定期执行。

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

答案 1 :(得分:0)

这是一个有效的示例 该示例将每5秒发送一次请求。根据需要进行更改

        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