Skip to content
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

Flow builder does not cooperate for cancellation #2000

Closed
pashko opened this issue May 7, 2020 · 2 comments
Closed

Flow builder does not cooperate for cancellation #2000

pashko opened this issue May 7, 2020 · 2 comments

Comments

@pashko
Copy link

pashko commented May 7, 2020

I am seeing some odd behaviour when canceling Flow collection. In the following example:

runBlocking {
    val flow = flow {
        while (isActive) {
            emit(Unit)
        }
    }
    val job = launch(Dispatchers.Default) {
        flow.collect {
            if (isActive) {
                println("active")
            } else {
                println("not active")
            }
        }
    }
    delay(100)
    job.cancelAndJoin()
}

I expect the collection as well as the flow builder to be canceled, but actually the builder continues producing values and the collector keeps accepting them (printing "not active"), and isActive in the builder returns true.
Now to make things weirder, if I remove the dispatcher from launch, the collector continues to print "active" even after cancelation, and if after that I add .flowOn(Dispatchers.Default) to the flow, everything works as expected.
Is this a bug or am I missing something in how Flow works?

@zach-klippenstein
Copy link
Contributor

I believe this is a duplicate of #1265.

@elizarov
Copy link
Contributor

elizarov commented May 8, 2020

It is not really a duplicate, because #1261 uses flowOn and that's going to be fixed soon. The code here runs into another problem. Look at this line:

val flow = flow {
        while (isActive) { // where's `isActive` coming from? 
            emit(Unit)
        }
    }

The answer is that it coming not from the flow { ... }, but from the surrounding runBlocking which is active. We have the following plan for the inspection to flag issues like that: https://youtrack.jetbrains.com/issue/KT-38033

@elizarov elizarov closed this as completed May 8, 2020
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

No branches or pull requests

3 participants