frankelot
05/19/2021, 8:32 PMCoroutineScope
s
I have a class that allocates some resources on its constructor init { // }
and the client has to explicitly call .dispose()
when it's done with it (I'm on Android so this is done in onDestroy()
)
lateinit var foo : Foo
onCreate() {
foo = Foo() // resources get allocated (init openGL context, open a file, etc)
}
onDestroy() {
foo.dispose() // must not forget!
}
I was thinking that it would be really nice to have these resources cleaned up automatically (something like RAII in c++)
That got me thinking, if there was a way to get a callback when the parent coroutine scope is being cancelled... I could do the cleanup thenprivate val dispatcher = newSingleThreadContext("OpenGLDispatcher")
ephemient
05/19/2021, 8:43 PMfrankelot
05/19/2021, 8:45 PMephemient
05/19/2021, 9:24 PMlaunch {
suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation { dispose() }
}
}
but that seems like a terrible idea since it'll keep the scope alive forever until explicitly cancelledfrankelot
05/19/2021, 9:48 PM