如果没有数据,如何用API响应更新Room DB?

时间:2018-08-02 23:31:57

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

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

API

    @property
    def sqlquery(self):
        retry_flag = True
        retry_count = 0
        conn = pyodbc.connect("Driver={SQL Server};"
                              "Server=server1;"
                              "Database=db1;"
                              "Trusted_Connection=yes;")
        cursor = conn.cursor()
        while retry_flag and retry_count < 10:
            try:
                cursor.execute('''
        SET NOCOUNT ON;
        SELECT * FROM xx.y
        WHERE y = '%s'
        AND a = '%s'
        AND b = '%s'
        AND c = '%s'
        AND d = '%s' ''' % (1stplaceholder, 2nd, 3rd, 4th, 5th))
                retry_flag = False
            except:
                print("Retry after 1 sec")
                retry_count = retry_count + 1
                time.sleep(1)
        for row in cursor:
            if cursor is None:
                return False
            else:
                return row[19]
        conn.close()

FactoryData.class

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

我不确定该怎么做。感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

最后,我可以解决我的问题。

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