Skip to content

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

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

Open
dkhalanskyjb opened this issue Mar 6, 2023 · 1 comment
Open

Comments

@dkhalanskyjb
Copy link
Collaborator

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!

@qwwdfsad
Copy link
Collaborator

qwwdfsad commented Mar 7, 2023

A small historical note.

During our initial design, WhileSubscribed was designed for very specific UI-related use cases where SharedFlow lifecycle is tightly bound to the corresponding UI element Job, meaning that the liveness of the helper coroutines was never considered as a dedicated design choice. It is rather how things are played out (i.e. it was quite natural to express WhileSubscribed in terms of operators over infinite subscription flow).

We can (if we decide on it) either fix it ad-hoc or to use it as a driving force for #1065

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants