Home > Net >  Kotlin Coroutine: get List of (T) from Flow<sealed class <list of <T>>>
Kotlin Coroutine: get List of (T) from Flow<sealed class <list of <T>>>

Time:12-03

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"
        }
    }
}

CodePudding user response:

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.

  • Related