Hi, I've been trying out the latest kotlin-corouti...
# kotlin-native
k
Hi, I've been trying out the latest kotlin-coroutines 1.3.7-native-mt-1.4-M2 on iOS and running into some challenges. Code here is based on the flow documentation description for flowOn. https://kotlinlang.org/docs/reference/coroutines/flow.html I've also watched kotlinconf topic for kotlin native concurrency, so I understand objects are frozen, but for the life of me I can't figure out a combination that will allow me to set the value on StateFlow. I've tried numerous combinations and ultimately all paths throw the InvalidMutabilityException. Error occurs in the stateSetter call. Any help would be appreciated.
Copy code
typealias 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())
    }
}
Found a combination that worked.
l
could u share u solution? I use coroutine instead of flow in my use case
e
I’d love to see a solutin you came up with, too.
StateFlow
was not supposed to work correctly accross threads yet
k
Yeah, I'll post in a playground sample I have once I clean it up. @elizarov it's not working across threads. When I read through the issue for StateFlow I noticed that which led me something closer to an actor model. API for end-user is still very similar though and that was the real goal.
Pretty excited though, this was the missing puzzle piece for my SwiftUI app to largely leverage Kotlin for almost everything aside from UI without compromising the original architecture.
e
Looking forward to a sample!
k
@elizarov pushed up the changes here. https://github.com/CoreyKaylor/kotlin-mpp-flow-store
You can definitely see that if StateFlow was thread-safe it would clean everything up quite a bit.