我是android的新手,并且一直在为视图模型编写代码,我不知道如何管理来自存储库和远程服务器的数据,这是我到目前为止已经尝试过的方法,任何帮助将不胜感激。
这是我的存储库数据源
class RepositoryDataSource constructor(private val roomDataSource: QuranLocalDataSource,
private val remoteDataSource: RemoteDataSource) : Repository {
override fun saveParaData(paraData: List<ParaData>) { roomDataSource.getQuranDao().insertParaData(paraData) }
override fun saveSurahData(surahData: List<SurahData>) { roomDataSource.getQuranDao().insertSurahData(surahData) }
//get Parah list from db
override fun getParaFromDB(): LiveData<List<ParaData>> = roomDataSource.getQuranDao().getParaData()
//get SurahList from dm
override fun getSurahDataFromDB(): LiveData<List<SurahData>> = roomDataSource.getQuranDao().getSurahData()
//get parahList from server
override fun getParahListFromAPI() {
remoteDataSource.getParahListFromAPI()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ result ->
Completable.fromAction {
deleteParaData()
val data = result.body()
saveParaData(data?.get(0)!!.paraData)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : CompletableSubscriber {
override fun onSubscribe(@NonNull subscription : Subscription) {
}
override fun onCompleted() {
Log.i("Repository onCompleted", "DataSource has been Populated")
}
override fun onError(@NonNull e: Throwable) {
e.printStackTrace()
Log.e("onError", "DataSource hasn't been Populated")
}
})
},
{ error -> Log.e("ERROR", "{$error.message}") },
{ Log.d("getParahListFromAPI", "completed") })
}
//get surahList from server
override fun getSurahListFromAPI() {
}
}
这是我的存储库
interface Repository {
fun saveParaData(paraData: List<ParaData>)
fun getParaFromDB(): LiveData<List<ParaData>>
fun saveSurahData(surahData: List<SurahData>)
fun getSurahDataFromDB(): LiveData<List<SurahData>>
fun getParahListFromAPI()
fun getSurahListFromAPI()
}
这是我的视图模型
class ParahViewModel : ViewModel(){}