Sam
07/04/2024, 2:31 PMJob
becomes cancelled.
• Adding the suspend
modifier would give access to the currentCoroutineContext()
, but it doesn't seem appropriate since the function doesn't actually suspend.
• Adding a CoroutineScope
receiver would also give access to the coroutine context, but that also doesn't seem appropriate since the function doesn't launch any coroutines.
• I could use thread interrupts and call the function from a runInterruptible
block, but that seems like a lot of hard work, and it's JVM only
Which would you pick? Any established conventions for this? Maybe there's another option I haven't considered?Sam
07/04/2024, 2:34 PMephemient
07/04/2024, 2:34 PMcheckActive()
periodically?ephemient
07/04/2024, 2:35 PMSam
07/04/2024, 2:36 PMJob
, using ensureActive()
like you said, checking the thread interrupt status manually, or setting up some other variable to check.Sam
07/04/2024, 2:37 PMephemient
07/04/2024, 2:38 PMSam
07/04/2024, 2:39 PMThread.interrupted()
without introducing any coroutine dependencies, but only on JVM 😞ephemient
07/04/2024, 2:41 PMephemient
07/04/2024, 2:41 PMSam
07/04/2024, 2:43 PMisActive: () -> Boolean
to my function to break the explicit dependency on coroutinesephemient
07/04/2024, 2:48 PMSam
07/04/2024, 2:58 PMyield()
, which will do the trick for cancellability too. Maybe that's why there isn't another common pattern for this.kevin.cianfarini
07/04/2024, 3:08 PMsuspend
and does a while(isActive)
to ensure it cancels cooperatively.kevin.cianfarini
07/04/2024, 3:09 PMisActive: () -> Boolean
is probably better.louiscad
07/04/2024, 9:09 PMgildor
07/05/2024, 2:17 AMisActive
, which anyway would be implemented like { currentCoroutineContext().isActive }
Also if CPU heavy, explicitly wrapping content to appropriate dispatcher (like Default) makes it safe to call from any suspend function