I return a RxJava Single type as you see bellow :
private fun getSpeciesWrapper(
character: Character, getSpecieUseCase: GetSpecieUseCase, getPlanetUseCase: GetPlanetUseCase,
): Single<List<SpecieWrapper>> {
var name: String? = null
var language: String? = null
return Flowable.fromIterable(character.specieUrls)
.flatMapSingle { specieUrl -> getSpecieUseCase(specieUrl) }
.flatMapSingle { specie ->
name = specie.name
language = specie.language
getPlanetUseCase(specie.homeWorld)
}.map { planet ->
SpecieWrapper(name, language, planet.population)
}.toList()
}
As you see I have defined name
and language
variables in order to use them in the map section to create a list of Specie wrapper.
Is there any solution in RxJava2 that I could simplify the Single type by removing these local variables (name and language) ?
You can simply nest the map
call inside of the flatMapSingle
call:
private fun getSpeciesWrapper(
character: Character, getSpecieUseCase: GetSpecieUseCase, getPlanetUseCase: GetPlanetUseCase,
): Single<List<SpecieWrapper>> {
return Flowable.fromIterable(character.specieUrls)
.flatMapSingle { specieUrl -> getSpecieUseCase(specieUrl) }
.flatMapSingle { specie -> getPlanetUseCase(specie.homeWorld)
.map { planet ->
SpecieWrapper(specie.name, specie.language, planet.population)
}
}.toList()
}