Re: Flow scope cleanup
If I've created a scope that is tied to the application process let's call it
appscope
and I'm using that to collect a private stateflow in a class as shown below.
Do I risk leaking something when this class is garbage collected? I.e. do I need clean up the launch?
Copy code
private val flowA = StateFlow()
init {
appscope.launch {
flowA.collect{}
}
}
fun update() {
flowA.value = x
}
👌 2
l
leandro
10/30/2024, 10:13 AM
I was tempted to say that you do not need to worry about leaking if you're reading from e.g. a file in local disk because the OS will close the file descriptors when your process is terminated, but the emoji reactions to your message make me wonder what I might be missing.
s
Sam
10/30/2024, 3:43 PM
A
StateFlow
never terminates, so that
collect()
call will run forever. That means the coroutine will stick around until you cancel its scope. That leaves you, at a minimum, with a leaked reference to
flowA
and its latest
value
.
l
leandro
10/30/2024, 3:46 PM
I agree. If it's tied to the process, once the process is terminated, nothing would be left behind, right? if one e.g. launches a
collect()
to pipe something to somewhere intending to keep these in sync while the app "exists", that would be okay, or?
s
Sam
10/30/2024, 3:49 PM
Oh, okay, I just spotted that you said "when your process is terminated". Yes, everything will be cleaned up when the process ends. If we're talking about resource leaks, we're always going to be talking about things that outlive their intended lifecycle within the process. I believe @enighma is asking about what happens when the object is no longer reachable.
🙏 1
Sam
10/30/2024, 3:51 PM
Maybe I misunderstood, though. If the intention is for the coroutine to outlive its containing object, then it's not necessarily a leak, just a confusing design choice.