Hi all! I’m trying to use `NativeCoroutinesState` ...
# multiplatform
k
Hi all! I’m trying to use
NativeCoroutinesState
in KMP-NativeCoroutines library. But even when I update a StateFlow, it won’t trigger re rendering in SwiftUI side… Does anyone can help about it?
Swift code:
Copy code
struct ContentView: View {
	let greet = Greeting().greet()

	@StateViewModel var viewModel = HomeViewModel()

	var body: some View {
        VStack {
            Text(viewModel.uiState.text)
            Button(
                action: {
                    print(viewModel.uiState)
                    viewModel.onClick()
                    print(viewModel.uiState)
                }
            ) {
                Text("Button")
            }
        }
	}
}
Log:
Copy code
HomeUiState(text=5)
onClick: current HomeUiState(text=5)
Text(viewModel.uiState.text)
should show 5, but still keep showing initial state (0)
r
Hi! Could you share a code snippet of the ViewModel?
In order for state changes to propagate to SwiftUI you'll need to use KMM-ViewModel functions in your VM. The NativeCoroutinesState annotation alone just exposes the StateFlow as a property.
k
Hi! Here is the ViewModel code:
Copy code
class HomeViewModel: KMMViewModel() {

    @NativeCoroutinesState
    val uiState = MutableStateFlow(HomeUiState())

    init {
        viewModelScope.coroutineScope.launch {
            while (true) {
                delay(1000)
                uiState.update {
                    it.copy(count = it.count + 1)
                }
            }
        }
    }

    fun onClick(): HomeUiState {
        println("onClick: current ${uiState.value}")
        uiState.update {
            it.copy(count = 0)
        }

        return uiState.value
    }
}
r
Thanks the following should work:
Copy code
val uiState = MutableStateFlow(viewModelScope, HomeUiState())
Providing the
viewModelScope
to the StateFlow will make sure that any changes are propagated to SwiftUI.
Note: you’ll need to add the following import for that:
Copy code
import com.rickclephas.kmm.viewmodel.MutableStateFlow
k
Ah! So I need to use KMM’s MutableStateFlow. Thank you! It working well now! I would be very appreciate if you can update the README to note about it!
r
It’s already on my todo list to improve the documentation around those functions 😇