【问题标题】:How update Room DB with API response if there is not data?如果没有数据,如何使用 API 响应更新 Room DB?
【发布时间】:2018-08-02 23:31:56
【问题描述】:

如果我的数据库表为空,我正在尝试使用我的调用 api 的响应更新我的数据库(房间)并返回到我的 recyclerview

API

@GET("user/patient/")
Flowable<ResponsePatient> getPatients(@Header("Authorization") String userToken);

FactoryData.class

public Flowable<List<Patient>> getPatientFromApi(){
    String token = preferences.getValue(SDConstants.token);
    return apiNetwork.getPatients(token).map(new Function<ResponsePatient, List<Patient>>() {
        @Override
        public List<Patient> apply(ResponsePatient responsePatient) throws Exception {
            return PatientMapper.transform(responsePatient);
        }
    });
}


public Flowable<List<Patient>> listPatient(){

      return appDataBase.patientDao().listPatient()
            .switchIfEmpty(getPatientFromApi())
            .doOnNext(s -> appDataBase.patientDao().saveAll(s));

}

我不知道该怎么做。我很感激任何帮助。

【问题讨论】:

    标签: retrofit2 repository-pattern rx-java2 android-room


    【解决方案1】:

    终于可以解决我的问题了。

    public Flowable<List<Patient>> getPatient(){
       return getPatientFromlocal()
                .take(1)
                .filter(list -> !list.isEmpty())
                .switchIfEmpty(
                        Flowable.defer(() -> getPatientFromApi()));
    }
    
    public Flowable<List<Patient>> getPatientFromlocal(){
        return appDataBase.patientDao().listPatient();
    }
    
    public Flowable<List<Patient>> getPatientFromApi(){
        String token = preferences.getValue(SDConstants.token);
        return apiNetwork.getPatients(token).map(new Function<ResponsePatient, List<Patient>>() {
            @Override
            public List<Patient> apply(ResponsePatient responsePatient) throws Exception {
                return PatientMapper.transform(responsePatient);
            }
        }).doOnNext(new Consumer<List<Patient>>() {
            @Override
            public void accept(List<Patient> patients) throws Exception {
                appDataBase.patientDao().saveAll(patients);
            }
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      • 1970-01-01
      • 2022-07-21
      相关资源
      最近更新 更多