Hi guys. What is the best way to implement some lo...
# coroutines
d
Hi guys. What is the best way to implement some long running background work (like in attached code) using coroutines?
d
Copy code
launch(<http://Dispatchers.IO|Dispatchers.IO>) {
    while(isActive) {
        checkNewFilesInDir();
        publishStatus();
        delay(200);
    }
}
👍 1
Do you want this to run throughout the application's lifetime? Or is there a scope?
g
isActive is not really needed here, it will anyway be checked on coroutine start and delay, true will be also fine
But maybe isActive is more explicit
d
Force of habit. I don't like seeing
while(true)
g
Yeah, true, also a but uncomfortable with while(true)😅
d
Ha
b
Question is too abstract. If we're talkin about specific case you mentioned, probably you need to switch from polling to file observer (e.g. https://developer.android.com/reference/android/os/FileObserver for android / WatchService api gtom nio for jvm) and wrap it for example to
callbackFlow
d
Yes, the question is abstract to understand different usage of coroutines. Reading file here is just for example, there can be long running network communication for example, or some other work.
Yes I want this to run throughout the application's lifetime
d
In that case
GlobalScope.launch
should work for you. (Assuming you're not on android, which might be done slightly differently).
d
I'm on Android 🙂 I think I can use some Scope for Service
If I want to put some data into this infinite loop and get some result from it I should use Channels, right? Maybe something else?
d
You can use
Channels
or
Flow
.
d
Ok,
Flow
is something new for me. Thanks to all
g
I would recommend to use Flow instead of channel for such case
👍 1