Skip to content

Fix an explanation of flowOn Operator #4402

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged

Conversation

seyoungcho2
Copy link
Contributor

@seyoungcho2 seyoungcho2 commented Mar 31, 2025

In this part, it says :

Otherwise, if changing dispatcher is required, it collects flow emissions in one coroutine that is run using a specified [context] and emits them from another coroutines with the original collector's context

and this explanation is reversed.

If flowOn passes CoroutineDispatcher, then the flow's emissions are performed in a coroutine running with the specified CoroutineContext not collector's context. The collector's original context is used to collect values emitted from the flow.

You can easily configure this by running below code.

val numberFlow: Flow<Int> = flow {
    for (number in 1..3) {
        println("[${Thread.currentThread().name}] Emitting: $number")
        emit(number)
        delay(1000)
    }
}

fun main() = runBlocking<Unit> {
    numberFlow
        .flowOn(Dispatchers.IO) 
        .collect { value ->
            println("[${Thread.currentThread().name}] Collected: $value")
        }
}

The result of code is:

[DefaultDispatcher-worker-1 @coroutine#2] Emitting: 1
[main @coroutine#1] Collected: 1
[DefaultDispatcher-worker-1 @coroutine#2] Emitting: 2
[main @coroutine#1] Collected: 2
[DefaultDispatcher-worker-1 @coroutine#2] Emitting: 3
[main @coroutine#1] Collected: 3

Process finished with exit code 0

The new coroutine(coroutine#2) is using DefaultDispatcher-worker-1 of Dispatchers.IO. And runBlocking Coroutine(coroutine#1) is collecting the value.

@seyoungcho2 seyoungcho2 force-pushed the feature/fix-flowOn-description branch from cd94f09 to 7d3926d Compare March 31, 2025 14:30
@dkhalanskyjb
Copy link
Collaborator

Thanks!

@dkhalanskyjb dkhalanskyjb merged commit 8b32c4e into Kotlin:develop Apr 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants