L
L
Lordao2019-03-19 16:15:33
Kotlin
Lordao, 2019-03-19 16:15:33

How to execute methods one by one in rxjava?

There is a repository where datasource is injected . This repository has two methods - loadLocal and loadRemote .
Initially, loadLocal is called, and if there are no records in the local database, then we call the loadRemote method, where the data is already received from the server in the form Single<List<Item>>. Then we must return already Flowable<List<Item>>from the local database after we have already added certain data from the server. How to competently perform the sequence, so that after receiving Single<List<Item>>from the server all the necessary data is extracted from it, thrown into the database and already returning the list from the database itself?

class ItemRepository @Inject constructor(private val dataSource: DataSource) {

    fun loadLocal(forceRemote: Boolean): Flowable<List<Item>> {
        return if (forceRemote) {
            loadRemote()
        } else {
            dataSource.loadLocal(false).filter { !it.isEmpty() }.switchIfEmpty(loadRemote())
        }
    }

    private fun loadRemote(): Flowable<List<Item>> {
        dataSource.loadRemote(false).map { list ->
            list.map { item ->

                /*code*/
                /*Вытягиваем данные из объекта и закидываем в разные таблицы БД*/
                
                with(dataSource) {
                    addItem(item)
                    addDetails(listDetails)
                    addItemDetails(listItemDetails)
                }
            }
        }
        return dataSource.loadLocal(false)
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2019-03-19
@Lordao

All db methods must return Completable

ds.loadRemote()
    . switchMap{
          ds.add1(...)
             .andThen(ds.add2(...))
             .andThen(ds.add3(...))
             .andThen(ds.loadLocal())
    }

About something like this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question