'Create Single from other singles and completable
I have a repository that returns Single<List<Table>>. This repository calls a datasource that creates a network call to return these objects from somewhere else (datasource returns Single<List<Table>>) . Once this data is acquired I need to make a local query to compare with the local database on a 1 to 1 basis (for each Table a new local query needs to be consulted and the original Table will change, local query returns Single<Table>). Once that item has changed I need to save it locally (it returns Completable). And once that is done I need to return this changed Single<List<Table>>
TLDR:
- Get list from server
Single<List<Table>> - loop each item from that list
- for each item check something in local database(local db returns
Single<Table>) - change original item based on local database
- save that changed item into local db, returns
Completable - return changed list
Single<List<Table>>
This is the code I got
fun getTables(param1: String): Single<List<Table> {
remoteDataSource.getRemoteTables()
.map { tables ->
tables.map { table ->
localDatasource.findById(table.id)
.subscribe({
val newTable = Table(table.id, it.name)
localDatasource.save(newTable)
//and here is when I realized I don't like rxjava.
},{})
}
}
}
I have no idea how to make this. Any help will be apreciated.
Solution 1:[1]
You can use a set of flatMap operators:
remoteDataSource.getRemoteTables()
.flattenAsFlowable { it }
.flatMapSingle { table ->
localDatasource.findById(table.id)
.flatMapCompletable { table2 ->
val newTable = Table(table.id, table2.name)
localDatasource.save(newTable)
}
.toSingleDefault(table)
}
.toList()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | akarnokd |
