Hi, Can we pause and resume a coroutine job?
# coroutines
d
Hi, Can we pause and resume a coroutine job?
l
No, usually, we use Flow with the xxxLatest operators to stop or start something. What's your use case?
u
• You can use suspend(Cancelable)Coroutine and hold on to the continuation instead of resuming it. Then, later you can resume it at any time. • You might also be able to write a pauseable dispatcher. • In general “no”.
l
Pausable dispatchers are often a bad idea, because they can lead to leaks, unused resources held, aka memory or resource leaks
d
My use case is to download a file in background and pause and resume the coroutine intermittently based on certain conditions. @louiscad could you please share any examples of flow getting paused and resumed ?
u
I assume you are using blocking IO on Dispatchers.IO. For pausing of blocking IO, it will be even harder. I see no way to pause a blocking operation. Either interrupt it or wait till it’s done. Pausing a coroutine will always work on a suspended coroutine only.
g
I think for this case, it must be a feature of your downloader, when you can just suspend on particular condition before/after each of buffer reads, you can use mutex or similar primitives to suspend until it unlocked Attempt to use pausable dispatcher is probably a bad idea, you should be explicit and have some "pause" point in your code
5
👍 3
s
I've toyed with this once, since I read an article talking about this topic using promises, and non-blocking/suspension from another language. Here is a toy implementation, but it works.
Untitled.cpp
z
+1 to what Andrey said but also because this sounds like business logic, not coroutines plumbing.