Hello guys, i have a question about background fun...
# coroutines
u
Hello guys, i have a question about background function processing using Coroutines! My question is that how could launch a coroutine for processing a task take a long time like sending message to cusotmer. All of my application’s API`s are sending messages to customer at the last step in the business logic, but sending message takes long time. So i wrote the code down below…
Copy code
suspend fun main() {
    route()
}

suspend fun route() = coroutineScope {
    logger.warn { "start rout! scope: $this, context: $coroutineContext" }
    service()
    logger.warn { "routing finished! scope: $this, context: $coroutineContext" }
}

suspend fun service() = coroutineScope {
    logger.warn { "service executed! scope: $this, context: $coroutineContext" }
    sendMessage("inner")
    logger.warn { "service finished! scope: $this, context: $coroutineContext" }
}

fun CoroutineScope.sendMessage(string: String) = launch {
    delay(3000)
    logger.warn { "sended message : $string, scope: $this, context: $coroutineContext" }
}

private val logger = KotlinLogging.logger {}
What I wanted for the code is route function is ends before service function that launch coroutines that sending message. But the code wasn’t. So how can i finish rout function not waiting until the service function finished?
d
Copy code
suspend fun CoroutineScope.service() = launch {
    logger.warn { "service executed! scope: $this, context: $coroutineContext" }
    sendMessage("inner")
    logger.warn { "service finished! scope: $this, context: $coroutineContext" }
}
coroutineScope {}
builder waits until all children coroutines are finished
u
@denis090712 Then, how to make parent coroutine not waiting it’s children coroutines are finished?
d
use
launch
or
async
builders to do any work “in background”
r
I think what you're looking for is a solution comparable to the one I answered here at another question: https://kotlinlang.slack.com/archives/C1CFAFJSK/p1689492022753919?thread_ts=1689490826.021019&cid=C1CFAFJSK