I am trying to save the data on the server to the local database with Room. Since these tables are related to each other, I want the insertion to be done in order.I listen to these operations with RxJava. For example i have school's and season's tables and and that's how I add the data:
fun insertAllSchools(vararg schools: School):Completable=dao.insertAll(*schools)
fun insertAllSeasons(vararg seasons: Season):Completable=dao.insertAll(*seasons)
When I create a separate method for each table, the insertion process is done, but I have to write a disposable method for each of them. Like this:
fun insertAllSchools(allData:ResponseAll){
if(allData.schoolList!=null){
disposable.add(
repositorySchool.insertAll(*allData.schoolList.toTypedArray())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableCompletableObserver(){
override fun onComplete() {
Log.d(TAG,"OnComplete")
}
override fun onError(e: Throwable) {
Log.e(TAG,"Error"+e.localizedMessage)
}
})
)
}
}
When one is complete, I call the other method, but this time there is a lot of unnecessary code.
I have tried different methods to combine these completable methods and work sequentially, but it does not add to the database even though it appears in the logs.
For example, I tried to combine it this way:
if(allData.schoolList!=null){
mObservable = Observable.fromArray(
repositorySchool.clearAllData(),
repositorySchool.insertAll(*allData.schoolList.toTypedArray())
)
disposable.add(
mObservable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableObserver<Completable>() {
override fun onComplete() {
Log.d(TAG,"onComplete")
isDataLoad.value = true
}
override fun onNext(t: Completable) {
Log.d(TAG,"onNext"+t)
}
override fun onError(e: Throwable) {
Log.e(TAG,"onError")
}
})
)
}
I do not receive any errors. How can I combine these completable methods and make them work sequentially. Thanks!
Edit(Solution): It works like this:------------>
if(allData.schoolList!=null) {
disposable.add(
repositorySchool.clearAllData()
.andThen(Completable.defer { repositorySchool.insertAll(*allData.schoolList.toTypedArray()) })
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableCompletableObserver() {
override fun onComplete() {
isDataLoad.value = true
}
override fun onError(e: Throwable) {
Log.e(TAG,""+e.localizedMessage)
}
})
)
}