Is there any alternative in Kotlin for C#'s AutoResetEvent?

203 Views Asked by At

I saw this post where it uses this event and I would like to know if there is any similar alternative in Kotlin, since I would like to use the WaitOne method that it uses for the return.

Example code:

   fun exampleMethod(): String{

    var command = "example string"
    //do someting with this string

    return command

}

I want to run this method continuously and receive the value of my variable command of the return every time it runs on the loop.

1

There are 1 best solutions below

0
flamewave000 On

So I just ran into a situation like this and was missing my good old AutoResetEvent. Kotlin does have great coroutine controls like Flows that can be used for signalling. I made a class that wraps this design pattern so its purpose is easier to read when used.

/** A coroutine synchronization event that suspends coroutines until a signal is sent. */
class SyncSignal(signaled: Boolean = false) {
    private val signal = MutableStateFlow(signaled)
    private val filteredSignal = signal.filter { it }.take(1)
    /** Suspend the current coroutine until it recieves a signal to resume */
    suspend fun await() = filteredSignal.collect()
    /** Sets the state to signaled allowing one or more coroutines to resume */
    fun signal() = signal.compareAndSet(expect = false, update = true)
    /** Resets the state to nonsignaled, causing coroutines to suspend */
    suspend fun reset() = signal.compareAndSet(expect = true, update = false)
}

val event = SyncSignal()
runBlocking { 
    launch {
        println("Wait 1")
        delay(200)
        event.await()
        println("1")
    }
    launch {
        println("Wait 2")
        delay(100)
        event.await()
        println("2")
    }
    launch {
        delay(300)
        println("RELEASE!")
        event.signal()
        event.reset()
        event.await()
        println("Tada!")
    }
    launch {
        delay(400)
        event.signal()
    }
}
/*
Wait 1
Wait 2
RELEASE!
2
1
Tada!
*/

Let me know if you can see any issues with the implementation. I tried making an AutoSyncSignal, but I ran into a lot of issues trying to get the first awaiting coroutine to reset the signal without getting dead-locked.

You can try it on the Kotlin Playground