Created
October 20, 2014 12:33
-
-
Save Centaur/97a22fb41e293968ff03 to your computer and use it in GitHub Desktop.
dispatcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package flux | |
/** | |
* Created by IntelliJ IDEA. | |
* User: xf | |
* Date: 14/10/20 | |
* Time: 下午5:49 | |
*/ | |
trait Payload[T] { | |
def content: T | |
} | |
trait Dispatcher { | |
var _lastID = 1 | |
var _prefix = "ID_" | |
var isDispatching = false | |
type Callback[T] = T => Unit | |
var callbacks = Map.empty[String, Callback[_]] | |
var _isPending = Map.empty[String, Boolean] | |
var _isHandled = Map.empty[String, Boolean] | |
var _pendingPayload: Any | |
def register[T: Payload](callback: Callback[T]): Unit = { | |
val newId = s"$_prefix$_lastID" | |
callbacks = callbacks.updated(newId, callback) | |
_lastID += 1 | |
} | |
def unregister(id: String): Unit = { | |
callbacks = callbacks - id | |
} | |
def waitFor(ids: Seq[String]): Unit = { | |
} | |
def dispatch[T: Payload](payload: T): Unit = { | |
_startDispatching(payload) | |
try { | |
for((id, callback) <- callbacks if !_isPending(id)) { | |
_invokeCallback(id) | |
} | |
} finally { | |
_stopDispatching() | |
} | |
} | |
protected def _invokeCallback(id: String): Unit = { | |
_isPending = _isPending.updated(id, true) | |
callbacks(id).apply(_pendingPayload) | |
_isHandled = _isHandled.updated(id, true) | |
} | |
protected def _startDispatching[T: Payload](payload: T):Unit = { | |
val unset = {case (k,v) => (k, false)} | |
_isPending.map(unset) | |
_isHandled.map(unset) | |
_pendingPayload = payload | |
isDispatching = true | |
} | |
protected def _stopDispatching(): Unit = { | |
_pendingPayload = null | |
isDispatching = false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment