May be a silly question, but can a `Job` `join()` ...
# coroutines
r
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
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
coroutineScope
?
I think you want to add your
Job
as a child of some other
Job
?
r
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
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*/ }