Arjan van Wieringen
05/30/2022, 8:22 AMEffectDispatcher
two ways:
// as a suspending function
interface EffectDispatcher<E> {
suspend fun dispatchEffect(effect: E)
}
// return a job
interface EffectDispatcher<E> {
val scope: CoroutineScope
fun dispatchEffect(effect: E): Job
}
As far as I understand:
In the suspending case (1st) it is the responsibility of the callee to provide a coroutinescope, and in the case of the 2nd the EffectDispatcher itself has a scope in which the effects launch and the callee gets a reference to the dispatched effect job, maybe to cancel it or something, or can cancel every running job with scope
.
Is this correct? As my preference goes I'd go for the 2nd option.
EDIT:
Option number 3 would be to have EffectDispatcher<E>
implement CoroutineScope
. I like that one best actually.Robert Williams
05/30/2022, 9:21 AMdispatchEffect
suspendRobert Williams
05/30/2022, 9:22 AMRobert Williams
05/30/2022, 9:22 AMRobert Williams
05/30/2022, 9:23 AMRobert Williams
05/30/2022, 9:25 AMcoroutineScope
blockRobert Williams
05/30/2022, 9:41 AMdispatchEffect(effect: E) = scope.launch {
//the suspending code you actually wanted to write
}
So all you've done is adding extra boilerplate which should be done by the callerArjan van Wieringen
05/30/2022, 10:57 AMinterface EffectDispatcher<E> : CoroutineScope {
fun dispatchEffect(effect: E)
}
class Store<S, A, E>(
....
override val coroutineContext: CoroutineContext = ....
) : .... , EffectDispatcher<E> {
....
override fun dispatchEffect(effect: E) {
launch {
effectHandler.reduceEffect(state, effect, this@Store) // <-- reduceEffect is suspend
}
}
}
And the callee:
val store = Store(... coroutineContext = ...)
store.dispatchEffect(..)
Arjan van Wieringen
05/30/2022, 11:01 AMRobert Williams
05/30/2022, 11:14 AMArjan van Wieringen
05/30/2022, 11:15 AMRobert Williams
05/30/2022, 11:16 AMlaunch
was the "best case" I really meant it - if you try to do anything fancy in the dispatcher you could break things really badly really fastRobert Williams
05/30/2022, 11:17 AMArjan van Wieringen
05/30/2022, 12:00 PM