rickclephas / KMP-ObservableViewModel

Library to use AndroidX/Kotlin ViewModels with SwiftUI
MIT License
569 stars 29 forks source link

On iOS state is not updating the views. #30

Closed oianmol closed 1 year ago

oianmol commented 1 year ago

Hi! Thanks for creating KMMViewModel! 🙇🏼

I have started using KMMViewModel like this, also I have setup the extension for Kmm_viewmodel_coreKMMViewModel like mentioned in the docs.

class LoginViewModel() : KMMViewModel() {
    @NativeCoroutinesState
    val uiState = MutableStateFlow(LoginUIState())
}

on iOS I was able to initialise the VM in my View

struct LoginScreen: View {
    @ObservedViewModel var viewModel : LoginViewModel

    init() {
        self.viewModel = LoginViewModel()
    }

    var body: some View {
          viewModel.uiState // this never updates
      }
}

The problem is that the uiState never updates even if the ViewModel emits new values to the state flow , am i doing something wrong here ?

rickclephas commented 1 year ago

Hi! The only thing missing is the KMM-ViewModel constructor for MutableStateFlow:

- val uiState = MutableStateFlow(LoginUIState())
+ val uiState = MutableStateFlow(viewModelScope, LoginUIState())

That should make sure to propagate state changes to iOS.

oianmol commented 1 year ago

Ohhh! The MutableStateFlow that you have created ! com.rickclephas.kmm.viewmodel.MutableStateFlow ! Please rename it to something like RickMutableStateFlow 😛 I couldn't have guessed that 😆