Hi all :wave: I have a (potentially) dumb questio...
# coroutines
f
Hi all 👋 I have a (potentially) dumb question regarding
CoroutineScope
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()
)
Copy code
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 then
For context, I'm using coroutines to init and teardown an openGL context All openGL calls must then be done in the thread the context is first created in so I'm using
Copy code
private val dispatcher = newSingleThreadContext("OpenGLDispatcher")
e
if you're on Android, why not LifecycleObserver?
f
fair point, I could use LifecycleObserver (and probably should)
just got curious about if it could be done with coroutines
e
as a total hack,
Copy code
launch {
    suspendCancellableCoroutine { continuation ->
        continuation.invokeOnCancellation { dispose() }
    }
}
but that seems like a terrible idea since it'll keep the scope alive forever until explicitly cancelled
f
yeah, agree, I think I'm going to stick with LifecycleObserver