katokay
06/20/2020, 5:29 PMtypealias Reducer<TState> = (TState, Action) -> TState
@OptIn(ExperimentalCoroutinesApi::class)
open class KStore<TState:Any>(initialState: TState, private val reducer: Reducer<TState>) {
private val state = MutableStateFlow(initialState)
private fun currentState() = state.value
private fun setState(newState: TState) {
state.value = newState
}
fun dispatch(action: Action) {
val currentGetter: () -> TState = ::currentState
val stateSetter: (TState) -> Unit = ::setState
val stateChanges = when(action) {
is FlowAction -> action.toFlow()
else -> flow { emit(action )}
}.map {
reducer(currentGetter(), it)
}.flowOn(Dispatchers.Default)
println("Got state changes")
stateChanges.onEach {
stateSetter(it)
}.launchIn(UIScope())
}
//callback method for pushing back to swift, hopefully a better alternative can be found
fun listen(onStateChange: (TState) -> Unit) = runBlocking {
state.onEach {
onStateChange(it)
}.launchIn(UIScope())
}
}
katokay
06/21/2020, 11:50 PMLuoqiaoyou
06/22/2020, 2:47 AMelizarov
06/22/2020, 7:22 AMStateFlow
was not supposed to work correctly accross threads yetkatokay
06/22/2020, 12:57 PMkatokay
06/22/2020, 1:02 PMelizarov
06/22/2020, 2:53 PMkatokay
06/24/2020, 12:14 AMkatokay
06/24/2020, 12:15 AM