```fun main() = runBlocking { test() } suspen...
# coroutines
d
Copy code
fun main() = runBlocking {
    test()
}

suspend fun test() {
    val job = coroutineScope {
        launch {
            delay(5000)
        }
    }
    println("job = $job")
}
I need to have a reference to the job when it’s running. But the print doesn’t seem to execute until 5 sec later. What would be the correct way to achieve this?
f
It's because you are launching a new Coroutine. If you would have written print just after delay then since they are in the same Coroutine context they will be executed synchronously
Ohh didn't realize you are trying to print job. Sorry what do you really want to do with job? You want to wait job for to finish and do something?
d
I need to start some other tasks in this suspend function. But I also need to get a reference to the job so I can cancel it later
The thing is it has a be in a suspend function.
is it even doable?
f
You can cancel the job as long as you have a reference to it
d
Yes. but I won’t have the job until the coroutineScope returns. It won’t return until the job is finished
t
Copy code
coroutineScope
suspends until all child jobs finish, this explains your delay. inside
coroutineScope
you have
this
👍🏾 1
d
so there is no way in a suspend function to start a new coroutine and let it run while I get the job reference?
t
you say “new coroutine” but what you mean I guess is
CoroutineScope
? inside
coroutineScope
this
refers to the scope which also consists of the Job AFAIK
o
you should do:
Copy code
coroutineScope {
  val job = launch { delay(5000) }
 println("job = $job")
}
👍 2
t
that would be a more typical usage, yes
but
coroutineScope { this.coroutineContext }
also contains a job AFAIK
d
coroutineScope {} starts a new coroutineScope based on the current one that launched suspend function, correct?
o
based on the current suspend context, which is similar but not the same
all suspend functions have a
coroutineContext
available inside them
d
Let’s say we do Coroutine(coroutineContext) in a suspend function. is it the same as coroutineScope {}
o
I presume you mean
CoroutineScope(coroutineContext)
-- no,
coroutineScope
also opens a new job, and if the current
coroutineContext
has a
Job
, the new one is a child of it
d
what do you mean by a child of it. the doc says ” The provided scope inherits its coroutineContext from the outer scope, but overrides the context’s Job.”
I am new to coroutine. I am sorry if I ask too many quesitons.
d
I will read it again. Thank you very much!