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

kingsley

03/04/2017, 7:35 AM
I have a setup like this one:
Copy code
// File A: Some repository
fun fetchFooAsync = async(CommonPool) { ... }

// File B: Android activity
private val job = Job()

fun loadFooIntoUI() {
  launch(Android + job) {
    fetchFooAsync().await()
    ...
  }
}
When the activity in B is getting destroyed, I can easily call
job.cancel()
, and the coroutine in
loadFooIntoUI
is canceled correctly. However, the
fetchFooAsync
call still continues indefinitely. Is there a way to neatly cancel everything altogether without having to explicitly pass
job
to
fechFooAsync
?
👍 1
d

deviant

03/04/2017, 9:31 PM
kingsley: i managed it in this way:
Copy code
fun async(block: suspend CoroutineScope.() -> Unit) {
        launch(Android + job, block = block)
    }
inside Base Activity (or other lifecycle element like fragment) and use my version of async instead of launch
k

kingsley

03/04/2017, 11:50 PM
Yes @deviant this works just the same as my example. Since you're in an activity anyway, I don't really mind passing the job around. However, to make the original async cancel aware, I'd also need to explicitly supply the job, which is the part that doesn't feel right to me.
3 Views