Home > Software design >  Kotlin parallel flow
Kotlin parallel flow

Time:01-28

How set flow to run operation asynchronously like parallel() in java?

IntStream.range(0, size)
                .boxed()
                .parallel()
                .map(this::doSomethingLong)
                .collect(Collectors.toList())

I wanna do some long operation in flow asynchronously

CodePudding user response:

In your case you can do something like this:

// Perform everything on a background thread using flowOn operator
fun simple(size: Int): Flow<Int> = flow {
    for (i in 0..size) {
        emit(i)
    }
}.transform { it ->
    emit(doSomethingLong(it))
}.flowOn(Dispatchers.Default)

fun main() {
    runBlocking {
        simple().collect { it ->
            println(it) // Collect on main thread
        } 
    }
}

Note that collecting happens in the context of the calling coroutine. Therefore if you want to collect on a different thread, you can specify it, for example, like this

withContext(Dispatchers.Main) {
    simple().collect { ... }
}
  • Related