'Launch one Coroutine at a time - Kotlin

We have a button in the UI, which, when pressed, will make some remote network call in its own coroutine. However, if the user spams the button for whatever reason, it is possible that the remote data might somehow get corrupted. We would like to prevent this by discarding all requests until the current one is completed.

There are many ways to do this. I have create a simple extension function on CoroutineScope to only launch if the CoroutineScope is not active. This is what I have created:

Extension Function

fun CoroutineScope.safeLaunch(dispatcher: CoroutineDispatcher, block: () -> Unit): Job {
    return if (!isActive) {
        launch(dispatcher) {
            block()
        }
    } else {
        launch {}
    }
}

Example Use

fun loadNotifications() {
    viewModelScope.safeLaunch(IO) {
        getNotifications.invoke() // Suspend function invoke should only be from a coroutine or another suspend function
    }
}

The problem is, the above won't compile as I get an error saying

Suspend function invoke should only be from a coroutine or another suspend function

Does anyone know what I'm doing wrong or how to make it work?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source