Search code examples
kotlinandroid-servicekotlin-coroutinescoroutine

How to call suspend function from Service Android?


How to provide scope or how to call suspend function from Service Android? Usually, activity or viewmodel provides us the scope, from where we can launch suspend but there is no similar thing in Service


Solution

  • 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