Slide 34
Slide 34 text
Flux
Dispatcher
class FluxDispatcher(
private val coroutineCxt
: CoroutineContext = CoroutineName(
"FluxDispatcher"
) + Dispatchers.
Default
) {
private val observerList
: MutableList> =
mutableListOf()
@Suppress
("UNCHECKED_CAST"
)
fun register
(
klass: KClass<
T>,
cb: suspend (action: T) -> Unit
): ActionObserver<
T> = ActionObserver(
klass = klass,
cb = cb
).also {
runBlocking(coroutineCxt
) {
observerList
.add(it as ActionObserver)
}
}
@Suppress
("UNCHECKED_CAST"
)
fun registerOnce
(
klass: KClass<
T>,
cb: suspend (action: T) -> Unit
): ActionObserver<
T> = ActionObserver(
klass = klass,
cb = cb,
dispatchCount = 1
).also {
runBlocking(coroutineCxt
) {
observerList
.add(it as ActionObserver)
}
}
fun unRegister
(observer: ActionObserver<
out FluxAction>) {
runBlocking(coroutineCxt
) {
observerList
.remove(observer)
}
}
fun dispatch
(action: T) {
runBlocking(coroutineCxt
) {
val execObserverList = observerList
.filter { it.isMyAction(action) }
Log.d(
"Flux"
,
"Dispatch action: ${action::
class.simpleName
}#${action.uid()
} for ${execObserverList.
size} observers."
)
execObserverList.
forEach { observer: ActionObserver
->
CoroutineScope(Dispatchers.
Default
).launch {
observer.observe(action)
withContext(
coroutineContext
) {
if (observer.
dispatchCount > 0) {
observer.
dispatchCount
--
if (observer.
dispatchCount == 0) {
unRegister(observer)
}
}
}
}
}
}
}
companion object {
private const val DISPATCH_UNLIMITED
: Int = -
1
}
data class ActionObserver<
T : FluxAction>(
val klass: KClass<
T>,
val cb: suspend (action: T) -> Unit
,
var dispatchCount
: Int = DISPATCH_UNLIMITED
) {
fun isMyAction
(action: T): Boolean = klass.isSuperclassOf(action::
class)
suspend fun observe
(action: T) = cb.invoke(action)
}
}
資料は公開する予定です
ので、後ほどご確認くださ
い!