How do you sync a SwiftUI TextField with your Kotl...
# multiplatform
h
How do you sync a SwiftUI TextField with your Kotlin ViewModel using MutableStateFlow?
🙌 1
The textfield requires a Binding, either via a @Published var in a Swift ObservableObject, or via
init(get: , set: )
. The latter requires no additional variable, but it causes
Binding<String> action tried to update multiple times per frame.
I just dont want to create another Swift ViewModel, because I already have a Kotlin ViewModel with Flows
n
Touchlab's KaMPKit has an example of sharing ViewModels. I'm not sure if it will meet your use case, but it would be a place to start. https://github.com/touchlab/KaMPKit
🙏 1
a
moko-mvvm
declarative-ui
branch contains example of integration kotlin viewmodel directly in swiftui without any additional swift viewmodels. https://github.com/icerockdev/moko-mvvm/blob/6a1d9da18b6650c9f364a0f72a8614fa906a596c/sample-apps/iosApp/iosApp/BookListViewBinding.swift#L19 here utils for this implementation - https://github.com/icerockdev/moko-mvvm/blob/6a1d9da18b6650c9f364a0f72a8614fa906a596c/sample-apps/iosApp/iosApp/mokoMvvmExt.swift
h
@alex009 So you do use Bindings.init(get, set) too. At least with MutableStateFlow instead, I get the warning
Binding<String> action tried to update multiple times per frame.
and it does not always update the state 🤔
h
Ahh, okay nice 😄
@alex009 Thanks. I’m curios, what do you think about simple fire
objectWillChange.send
right in the setter of the binding?
Copy code
func binding<T>(_ keyPath: KeyPath<Counter, MutableStateFlow>, t: T.Type) -> Binding<T> where T: Equatable {
        binding(flow: self[keyPath: keyPath], t: t)
    }
    
    func binding<T>(flow: MutableStateFlow, t: T.Type) -> Binding<T> where T: Equatable {
        .init(get: {
            flow.value as! T
        }, set: { new in
            if (new != flow.value as! T) {
                self.objectWillChange.send()
                flow.setValue(new)
            }
        })
    }
a
because flow can be change itself. in your case you will emit data to flow, but not read this flow
h
Yeah, thats right.