Skip to content

shareIn keeps coroutines alive even when there are no subscribers #3662

Open
@dkhalanskyjb

Description

@dkhalanskyjb

Consider this code:

        runBlocking {
            launch(CoroutineName("coroutines in flow")) {
                val flow = flow {
                    var i = 0
                    while (true) {
                        emit(i)
                        delay(100.milliseconds)
                        ++i
                    }
                }.shareIn(this, SharingStarted.WhileSubscribed(stopTimeout = 1.seconds))
                flow.first()
            }
            delay(2.seconds)
            println("breakpoint here")
        }

If we put a breakpoint at the designated println, in the debugger, we see several coroutines with coroutines in flow in their name. This is surprising: this is almost two seconds after the only subscriber of the flow in existence has finished its work, and shareIn was parameterized only to keep sharing for one second after the last subscriber is lost. However, the flow still keeps some coroutines.

Kudos to @zsmb13 for reporting this!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions