0

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 Service lifecycle

Can anyone help me with this?

Zain
  • 37,492
  • 7
  • 60
  • 84
Stack
  • 1,164
  • 1
  • 13
  • 26

1 Answers1

0

is it mandatory to cancel the coroutine after finishing the task ?

No, it is not mandatory. Usually coroutines are launched in a context of some CoroutineScope and CoroutineScope is tied to some lifecycle, usually Activity or Fragment. Coroutines are used to execute some task in a background thread in a sequential manner.

Method onHandleWork of JobIntentService class 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.

Since i am launching the coroutine on the onHandleWork it doesn't block the current thread.

Method onHandleWork is called on a background thread so you don't need to launch a coroutine there.

Sergio
  • 27,326
  • 8
  • 128
  • 149