Vikas Acharya
Vikas Acharya

Reputation: 4162

Is it possible to execute an ongoing job

I have a Job like below

job = GlobalScope.launch {
    delay(5000)
    runOnUiThread {
        some unwanted code
    }
}

This job will wait for 5 seconds to execute. And to cancel it before 5 seconds I'm calling

job?.cancel()

Now, Is there a way to execute this job before 5 seconds have reached ?

I'm looking for something like job?.forceExecute.ignoreDelays or job?.forceExecute.ignoreDelay("FirstDelay") if there is a option for name like delay(5000,"FirstDelay")

That would be so helpful for me to avoid boiler plate code.

Upvotes: 0

Views: 68

Answers (2)

Oya Canli
Oya Canli

Reputation: 2516

One possible solution I can think of is to use withTimeout instead of delay and for executing the task in case of time out, you can check for TimeoutCancellationException

GlobalScope.launch {
        try {
            withTimeout(5000){
                //Imagine checkThisCondition() is a suspension function which will check the condition you need and return boolean
                val condition : Boolean = checkThisCondition()
                if(condition){
                    executeTheTask()
                }
            }
        } catch (e : TimeoutCancellationException){
            executeTheTask()
        }
    }

Upvotes: 1

Ethan Choi
Ethan Choi

Reputation: 2409

Is there a way to execute this job before 5 seconds have reached ?

Answer

using nested job + coroutine cancellation

Try this

job = GlobalScope.launch {
    delayJob = GlobalScope.launch { delay(5000) }
        delayJob.join()

        runOnUiThread {
        some unwanted code
    }
}

// if you want ignore delay
delayJob.cancel()

Upvotes: 1

Related Questions