使用RxJava,Retrofit2和Realm(async)保留请求结果

时间:2016-04-28 17:50:59

标签: android multithreading realm retrofit2

我尝试连接到api,下载一些数据并将其保存到我的本地Realm数据库。要连接到api,我使用Retrofit2,返回一个Observable对象。我在异步时遇到问题,因为Realm明显告诉我,我不能在不同的线程上使用相同的域对象

这是我的代码(不工作)

new ServiceFactory(getContext()).createRetrofitService(PatientService.class)
            .getPatientsList(token)
            .subscribeOn(Schedulers.newThread())
            .doOnTerminate(() ->
                getActivity().runOnUiThread(() -> {
                    swipeLayout.setRefreshing(false);
                })
            )
            .map(PatientsList::getData)
            .flatMap(Observable::from)
            .subscribe(this::updatePatientCard);
}

这是updatePatientCard方法,它会抛出异常 java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.

private void updatePatientCard(Patient patient){
        String indirizzoResidenza = patient.getResidenza().getIndirizzo().getIndirizzo() + " - " + patient.getResidenza().getIndirizzo().getNcivico() + " - " + patient.getResidenza().getIndirizzo().getProvincia();
        boolean privato = patient.getTipoassistenza().contains("privato");
        PatientCardView card = new PatientCardView(patient.getGuid(), patient.getUniqueKey(), patient.getNome(), patient.getCognome(), patient.getDatan(), patient.getTelefono1(), indirizzoResidenza, patient.getSesso(), privato, patient.isScaduto(), patient.getPhoto());
        patientsList.add(card);
        rvAdapter.animateTo(patientsList);
}

方法animateTo simpy将元素添加到列表的正确位置

如果我在.observeOn(AndroidSchedulers.mainThread())步骤中使用subscribe应用程序冻结,那么我就无法使用它

0 个答案:

没有答案