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

rook

07/03/2019, 8:31 PM
May be a silly question, but can a
Job
join()
asynchronously? I’d like to append coroutines to a job dynamically and then have it complete when it runs out of running coroutines
b

bdawg.io

07/03/2019, 8:33 PM
What do you mean by dynamically? As long as the job, or one of its children, doesn't complete,
join
will continue to suspend (including if you spawn additional children)
d

Dominaezzz

07/03/2019, 8:33 PM
coroutineScope
?
I think you want to add your
Job
as a child of some other
Job
?
r

rook

07/03/2019, 8:44 PM
Basically
Copy code
val myJob = Job().apply{ invokeOnCompletion { /*some completion work*/ } }
val myContext = myJob + <http://Dispatchers.IO|Dispatchers.IO>

fun someWork() {
  repo.dataStream.onEach {
    launch(myContext) {
      //do stuff
    }
  }
}
is there a spot in there where I can theoretically start/stop the job?
s

streetsofboston

07/03/2019, 8:46 PM
when wrapping your `launch`es inside a
coroutineScope { ... }
, you make sure that that call to
coroutineScope { ... }
resumes only after all its child Jobs have finished
Copy code
val job = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>).launch {
    coroutineScope {
        repo.dataStream.onEach {
            launch {
                //do stuff
            }
        }
    }
    /*some completion work*/
}

job.invokeOnCompletion { /*some more completion work*/ }
3 Views