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

com.jtransc.async.signal.kt Maven / Gradle / Ivy

package com.jtransc.async

import com.jtransc.lang.Disposable

class Signal {
	private val callbacks = arrayListOf<(value: T) -> Unit>()

	private class SignalDisposable(val signal: Signal, val callback: (value: T) -> Unit) : Disposable {
		override fun dispose() {
			signal.remove(callback)
		}
	}

	fun removeAll() {
		callbacks.clear()
	}

	private fun remove(callback: (value: T) -> Unit) {
		callbacks.remove(callback)
	}

	fun add(callback: (value: T) -> Unit): Disposable {
		callbacks.add(callback)
		return SignalDisposable(this, callback)
	}

	fun once(callback: (value: T) -> Unit): Disposable {
		var handler: (T) -> Unit = {}
		handler = { value: T ->
			remove(handler)
			callback(value)
		}
		add(handler)
		return SignalDisposable(this, handler)
	}

	fun dispatch(value: T) {
		for (c in callbacks.toList()) c(value)
	}

	operator fun invoke(value: T) = dispatch(value)
	operator fun invoke(callback: (value: T) -> Unit) = add(callback)
}

fun Signal.dispatch() {
	return this.dispatch(Unit)
}

fun  Signal.pipeTo(that: Signal) {
	this.add { that.dispatch(it) }
}

fun  Signal.waitOneAsync(): Promise {
	val deferred = Promise.Deferred()
	this.once { deferred.resolve(it) }
	return deferred.promise
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy