I am using kotlin coroutines in my JobIntentService, So on onHandleWork I would launch my coroutine, once this tasks end, I need to clean up the resources by cancelling the Job. onDestroy called immediately after starting of the service, Since I am launching the coroutine on the onHandleWork it doesn't block the current thread.
Is it mandatory to cancel the coroutine after finishing the task ?
If so, When to release the coroutine resources in the android
Servicelifecycle
Can anyone help me with this?
No, it is not mandatory. Usually coroutines are launched in a context of some
CoroutineScopeandCoroutineScopeis tied to some lifecycle, usuallyActivityorFragment. Coroutines are used to execute some task in a background thread in a sequential manner.Method
onHandleWorkofJobIntentServiceclass is called on a background thread, so you can do long blocking operations here. I don't see the reason why you should launch a coroutine in this method. Just execute your task without launching the coroutine.Method
onHandleWorkis called on a background thread so you don't need to launch a coroutine there.