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

33
December 04, 2021, at 6:50 PM

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

READ ALSO
Ajax Search Posts and Ajax Load more

Ajax Search Posts and Ajax Load more

I'm not that yet super familiar with AJAX but I'm learning

56
Is there a Postgrest API equivalent for MySQL?

Is there a Postgrest API equivalent for MySQL?

I earlier worked on postgres sql database and created some functions there which i called using postgrest api via postman

76
Run tracert command in Python but stop at &quot;request timed out&quot;

Run tracert command in Python but stop at "request timed out"

I need to tracert an IP and I am doing it like this:

62