Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 790
Nurseyit Tursunkulov Avatar asked Aug 14 '20 02:08

Nurseyit Tursunkulov


Video Answer


2 Answers

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

like image 109
Saurabh Thorat Avatar answered Dec 15 '22 16:12

Saurabh Thorat


for me worked like that

import androidx.lifecycle.lifecycleScope
class ServiceLife : LifecycleService() {
    private var supervisorJob = SupervisorJob(parent = null)
    override fun onCreate()  {
        super.onCreate()
        val serviceJob = lifecycleScope.launch {
            //some suspend fun
        }
          supervisorJob[serviceJob.key]
          supervisorJob.cancel()
    }
}
like image 30
AllanRibas Avatar answered Dec 15 '22 16:12

AllanRibas