All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.fireflysource.common.coroutine.ChannelExtension.kt Maven / Gradle / Ivy

There is a newer version: 5.0.2
Show newest version
package com.fireflysource.common.coroutine

import kotlinx.coroutines.channels.Channel
import java.util.concurrent.atomic.AtomicBoolean

inline fun  Channel.pollAll(crossinline block: (T) -> Unit) {
    while (true) {
        val message = this.poll()
        if (message != null) block(message) else break
    }
}

class Signal {
    private val channel: Channel = Channel(Channel.UNLIMITED)
    private val notified = AtomicBoolean(false)

    suspend fun wait(): T = channel.receive()

    fun notify(e: T) {
        if (notified.compareAndSet(false, true)) {
            channel.offer(e)
        }
    }

    fun reset() {
        notified.set(false)
        channel.pollAll { }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy