简体   繁体   中英

Get reference to a coroutine job in coroutine scope

In kotlin coroutine, most standard builder methods(such as launch) return a reference to a job,

does the design in this is to keep those reference in somethings such as a map/list(manage launched jobs "manually") or is there a way to find a launched job in a given scope?

 scope.launch { /* starting a coroutine in scope */ }

is there a way later to get the launched coroutine reference without keeping a reference for the launched job returned by scope.launch or should we manage this ourselve(eg. keep reference returned by launch)?

you need to save a reference to the parent job

val job = Job()
val scope = CoroutineScope(Dispatchers.IO + job)
scope.launch {
    ...
    job.children // this return all jobs started in this scope
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM