Does Kotlin have something which works exactly the same as "DispatchWorkItem" in swift?

1.1k views Asked by At

I want to execute a particular function after some timeout or if some particular condition is met. I have done the same in swift using DispatchWorkItem and used

dispatchQueue?.asyncAfter(deadline: .now() + .seconds(10), execute: self.dispatchWorkItemForDevicesDiscovery!) 

to start the timer and after 10 seconds the associated disptachWorkItem gets executed.

How to do that in Kotlin?

1

There are 1 answers

0
Willi Mentzel On BEST ANSWER

You can use Kotlin's coroutines for that. You can create your own suspend function which checks a given condition any amount x of time.

suspend fun startConditionally(checkDelayMillis: Long = 10, condition: () -> Boolean, block: () -> Unit) {
    while (true) {
        if (condition()) { break }
        delay(checkDelayMillis)
    }

    block()
}


fun main() {
    var i = 0

    // make the condition be fullfilled after 1 sec.
    GlobalScope.launch {
        delay(1000)
        i = 1
    }

    GlobalScope.launch {
        startConditionally(condition = {
            i == 1
        }) {
            println("Hello")
        }
    }

    Thread.sleep(2000L)  // block main thread for 2 seconds to keep JVM alive
}

You will need to add a dependency because coroutines are not part of the standard library.

Here is what you need to put in your pom.xml (for Maven):

<dependency>
    <groupId>org.jetbrains.kotlinx</groupId>
    <artifactId>kotlinx-coroutines-core</artifactId>
    <version>1.1.0</version>
</dependency>

Additionally you need to activate them:

<plugin>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-maven-plugin</artifactId>
    ...
    <configuration>
        <args>
            <arg>-Xcoroutines=enable</arg>
        </args>
    </configuration>
</plugin>

Further reading