androidkotlinandroid-jetpack-composekotlin-coroutineskotlin-flow

How to transform Flow<T> to StateFlow<List<T>> in Kotlin?


There is a Flow like this:

val flow = flow {
    for (i in 1..100) {
      emit(i)
    }
  }

I need to display all the element in this flow on the screen, so I need to convert Flow<Int> to StateFlow<List<Int>>.

What should I do?

Note: Do not modify the code inside flow, similar to emit(list)

first edit

I need to use StateFlow<T>.collectAsStateWithLifecycle to display data on Screen.

If I use flowOf((1..100).toList()), then I need two Flow, which is of course a solution. But what I am looking for is to directly convert Flow<Int> to StateFlow<List<Int>>.


Solution

  • There isn't a better way than using toList. If you really wanted, you could use flow { emit(flow.toList()) }.