'Kotlin Coroutine: get List of (T) from Flow<sealed class <list of <T>>>
I have the following function that return Flow<sealed class <list of < T > > > ,
fun getItems() : Flow<Resources<List<Item>?>>
How can I get list of Item from this function?
where Resources class as fllow:
sealed class Resources<out T>(val data: T?) {
class Success<T>(data: T) : Resources<T>(data)
class Error(val throwable: Throwable) : Resources<Nothing>(null)
object Loading : Resources<Nothing>(null)
override fun toString(): String {
return when (this) {
is Success -> "Success: $data"
is Error -> "Error: ${throwable.message}"
is Loading -> "Loading"
}
}
}
Solution 1:[1]
Try this code:
val items: List<Item>? = getItems().first { it is Resources.Success }.data
It will pick the first Success emission from flow.
Note that first is a suspend function so you can call it from a coroutine only.
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 | Arpit Shukla |
