https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

Dmitry Khasanov

12/09/2019, 11:51 AM
Hi guys. What is the best way to implement some long running background work (like in attached code) using coroutines?
d

Dominaezzz

12/09/2019, 12:38 PM
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

gildor

12/09/2019, 12:42 PM
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

Dominaezzz

12/09/2019, 12:43 PM
Force of habit. I don't like seeing
while(true)
g

gildor

12/09/2019, 12:43 PM
Yeah, true, also a but uncomfortable with while(true)😅
d

Dominaezzz

12/09/2019, 12:43 PM
Ha
b

bezrukov

12/09/2019, 12:49 PM
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

Dmitry Khasanov

12/09/2019, 1:05 PM
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

Dominaezzz

12/09/2019, 1:08 PM
In that case
GlobalScope.launch
should work for you. (Assuming you're not on android, which might be done slightly differently).
d

Dmitry Khasanov

12/09/2019, 1:19 PM
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

Dominaezzz

12/09/2019, 1:38 PM
You can use
Channels
or
Flow
.
d

Dmitry Khasanov

12/09/2019, 1:42 PM
Ok,
Flow
is something new for me. Thanks to all
g

gildor

12/09/2019, 3:02 PM
I would recommend to use Flow instead of channel for such case
👍 1
2 Views