L
L
Lordao2019-03-27 18:36:17
Kotlin
Lordao, 2019-03-27 18:36:17

How to check if there is data in the database using rxjava2?

There is a method which returns Flowable<List<Item>>.Because of take(1) we receive the list, but we cease to receive updates from a DB. If you remove it and at the same time there will be no records in the database, then the list will not return as a result.
How can I check if there are records in the database and, if not, get data from the server and then return a local list?

fun loadItems(forceRemote: Boolean): Flowable<List<Item>> {
return if (forceRemote) {
            loadRemoteData()
        } else {
         itemDataSource.loadLocalItems().take(1).filter { !it.isEmpty() }.switchIfEmpty(loadRemoteData())
       }
}

private fun loadRemoteData(): Flowable<List<Item>> {
        return itemDataSource.loadRemoteItems().switchMap {
            itemsDataSource.addItems(it).andThen(itemDataSource.loadLocalItems())
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2019-03-28
@zagayevskiy

The database should return an empty list if there is no data. Further along the empty list, you can trigger a trip to the server.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question