https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

Aaron Stacy

01/16/2020, 3:01 AM
Hi friends, I'd like to observe a coroutine scope's cancellation. Is there an idiomatic way to do that? My use case is I'm working on something that multiplexes I/O connections (specifically Android binder IPC) within an app. More specifically, if an Activity and a Service both connect to the same service (i.e. Google Play services' location service), I'd like them to share the same binder connection, and if both get onDestroy, I'd like to unbind. The best solution I've come up with is to launch a coroutine from the scope's context, delay forever, and catch the cancellation exception:
Copy code
scopeToBeObserved.coroutineContext.launch {
  try {
    delay(FOREVER)
  } catch (ignored: CancellationException) {
    // ... unbind the service connection ...
  }
}
a

Aaron Stacy

01/16/2020, 2:57 PM
Thats a much better solution thank you so much!
2 Views