Is there a better way of writing this? `loadFavori...
# android
r
Is there a better way of writing this?
loadFavoriteStations()
returns a
Flow<List<T>>
The first
map
gives me a
List<T>
that I need to map hence the nested
map
calls.
a
try the kotlin Result API
r
?? @allan.conda
a
This article was helpful for me in understanding how to improve code like that: https://kotlin.christmas/2019/17 A bit dated and there is now an official kotlin Result API so you don’t have to write your own Result class like in the article. https://github.com/Kotlin/KEEP/blob/master/proposals/stdlib/result.md#limitations
basically in the end you will have more imperative, less nesting, and better error handling code
But if you just want some example how your code can be improved without much explanation, I would rewrite the code like this:
Copy code
private fun loadFavoriteWeather() = viewModelScope.launch(dispatcher) {
    val favoriteStations = weatherRepository.loadFavoriteStations()
    if (favoriteStations == null) { // more fine-grained error handling
        Log.e ("Failed to load stations")
    }
    val windInfo = favoriteStations.map { weatherRepository.loadWindInfo(it.name) }
    if (windInfo == null) {
        Log.e ("Failed to wind info")
    }
}
d
Check out
flatMap
and
onEach
.
g
What is your final goal, get Flow<T>? Or Flow<List<T>>? But in any case you need flatMap instead of map as Dominic suggested, because otherwise you getting Flow as result
r
flatMap
can be used