```class MyVieWModel(     private val repository: ...
# getting-started
u
Copy code
class MyVieWModel(
    private val repository: Repository,
    private val applicationCoroutineScope: CoroutineScope
) {
    fun foo() {
        applicationCoroutineScope.launch {
            delay(10_000)
            repository.doSomething()
        }
    }
}
is this pattern (using a injected coroutine scope that has longer life-time than a viewmodel does) and launching a coroutine in it considered bad? I think it is, since the launch lambda captures the repository field, however there is from what I know there is no field capture in kotlin/java, and it always captures viewmodel
this
thus leaking it (if screen is closed before the lambda returns) (if it captures just the repo, then it would be fine -- but there's no way to do that in kotlin?) am I correct?
e
If you’re targeting Android you should look into using WorkManager to do long-running tasks independently of view lifecycle. You can set the worker as expedited work to launch it immediately https://developer.android.com/develop/background-work/background-tasks/persistent/getting-started/define-work#expedited
u
thanks for the suggestion but I was precisely asking for that situation if I my assumptions are correct
c
> Any properties used inside the lambda body are captured by the lambda expression The Kotlin spec seems to say only
repository
will be captured, but I don't have the knowledge to be sure that's the case here. https://kotlinlang.org/spec/expressions.html#lambda-literals
e
you can look at the generated bytecode to be sure
I would expect the
suspend
lambda to capture
this@MyViewModel
at creation, then clear the reference after
repository
is used
u
okay so it is a bad pattern, right? if the suspend fun never returns/never ending flow etf, then its a permanent leak