Home > Blockchain >  Kotlin: How to call suspendable function without awaiting its result?
Kotlin: How to call suspendable function without awaiting its result?

Time:12-12

I want to trigger a function called initiateFulFillment inside the function confirmPayment, but I do not want to wait inside confirmPayment until the execution of initiateFulFillment is finished. This is because the result of confirmPayment does not depend on the call of initiateFulFillment.

It seems to be working when I use GlobalScope.launch to trigger initiateFulFillment, but I wonder if this is a good way of achieving what I want or whether there is some better way?

Because in my IDE I get a warning that GloablScope is a delicate API and it only should be used, when it has to be used.

fun confirmPayment(orderId: Int): Boolean {
    // * some validation *
    GlobalScope.launch {
        initiateFulFillment(orderId)
    }
    return true
}

suspend fun initiateFulFillment(orderId: Int) {
    // * initiating fulfillment *
}

CodePudding user response:

Since GlobalScope is typically used to perform application-lifetime work, you indeed should not use it for short or limited tasks, that are view/activity/fragment specific.

Using scope for this is fine, so you need to create a custom one for that. There are a lot of ways to create and setup a custom coroutine scope, I will show the most simple one.

val customScope = CoroutineScope(Dispatchers.IO   SupervisorJob())

...

fun confirmPayment(orderId: Int): Boolean {
    // * some validation *
    customScope.launch {
        initiateFulFillment(orderId)
    }
    return true
}

UPD: You should note, that if this code runs in some kind of a view model, and the user leaves the screen, scope can be cleared and thus it will not wait for work to finish.

UPD2: I use IO dispatcher in my example, it is suitable for network calls. However, if this is a some kind of computation and is not related to sending requests and waiting for responses, you should probably use Dispatchers.Default

  • Related