Hello! Can anyone tell me if there's a neater way ...
# announcements
s
Hello! Can anyone tell me if there's a neater way of doing this? I'm trying to essentially run some code after a specified delay, but I want to handle the case the function is called before it's actually finished executing.
Copy code
private var job: Job? = null
    private fun scheduleJob() {
        job?.cancel()
        job = flow<Void> {
            delay(mySpecifiDelay)
            doWork()
        }.launchIn(CoroutineScope(coroutineDispatcher))
    }
d
Might as well be using
GlobalScope
there.
Also, it doesn't look like you need a flow here, you can just
launch
.
To be clear, don't use
GlobalScope
, just store your
CoroutineScope
somewhere and re-use it.
s
Brain fart, good point, I can just do
Copy code
private fun scheduleJob() {
        job?.cancel()
        job = CoroutineScope(coroutineDispatcher).launch {
            delay(mySpecifiDelay)
            doWork()
        }
    }
Yeah I've been going back and forth on the best way of handling scopes, I'm injecting the coroutineDispatcher and I can never decide which pattern I prefer when it comes to getting hold of a scope
d
Well, if you're going to re-create it each time, just use
GlobalScope
. It's the same thing but less allocations.
a
Instead of injecting Dispatchers, I inject CoroutineScopes. It has been helping me much. Including having it in memory