How to call suspend function from Service Android?

You can create your own CoroutineScope with a SupervisorJob that you can cancel in the onDestroy() method. The coroutines created with this scope will live as long as your Service is being used. Once onDestroy() of your service is called, all coroutines started with this scope will be cancelled.

class YourService : Service() {

    private val job = SupervisorJob()
    private val scope = CoroutineScope(Dispatchers.IO + job)

    ...

    fun foo() {
        scope.launch {
            // Call your suspend function
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        job.cancel()
    }
}

Edit: Changed Dispatchers.Main to Dispatchers.IO

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)