rickclephas / KMP-ObservableViewModel

Library to use AndroidX/Kotlin ViewModels with SwiftUI
MIT License
576 stars 27 forks source link

How to create a Binding for SwiftUI? #31

Closed jnelle closed 1 year ago

jnelle commented 1 year ago

Hey thanks for the great library! :)

I'm having issues with creating a Binding Variable for SwiftUI. My KMM code is the following:

class CommonAuthViewModel : KMMViewModel(), KoinComponent {
    @NativeCoroutinesState
    var isLoggedIn: StateFlow<Boolean> =
        MutableStateFlow(viewModelScope, false)

    fun changeState() {
            isLoggedIn.value = true
        }
}

In XCode I faced the following error:

image

In my view I initialized the ViewModel like the following:

    @StateViewModel var authViewModel = AuthViewModel()

I'm also confused from XCode it shows that this variable is a Binding

image

I want to thank you for this library and also thanking for the good communication with the community, that is not a matter of course and I appreciate that very much!

rickclephas commented 1 year ago

Bindings are automatically provided for mutable properties. In your case isLoggedIn is converted to a read-only property due to the StateFlow return type. Changing the return type to MutableStateFlow will generate a mutable property.

Which will support bindings when combined with @StateViewModel (or one of the other property wrappers).

jnelle commented 1 year ago

Thanks, worked for me! :)