Hello. I am facing an issue where a StateFlow valu...
# compose-ios
m
Hello. I am facing an issue where a StateFlow value resets back to its original value even after updating it. This is only happening in iOS. The following code is in the commonMain of the shared module
Copy code
private val _isLoading: MutableStateFlow<Boolean> = MutableStateFlow(false)
internal val isLoading: StateFlow<Boolean> = _isLoading
I update this as usual in a view model class
Copy code
fun loadData() {
    _isLoading.update { true }
}
Composable
Copy code
@Composable
fun App(vm: SomeViewModel = SomeViewModel()) {

    LaunchedEffect(key1 = true) {
        vm.loadData()
    }

    val loading = vm.isLoading.collectAsState()
    println("Loading: ${loading.value}")

    MaterialTheme {
        Box(modifier = Modifier.fillMaxSize()) {
            Text("${loading.value}")
        }
    }
}
The log that gets printed is Loading: false Loading: true Loading: false This works perfectly fine in the android app. All the code exists in the shared module. Any help would be appreciated. Thank you
👍 1
p
Can you print the ViewModel instance. I think App is getting recompose and is creating a new instance
Now the reason why you don't see the false/true logs twice is because key = true in remember, try key = ViewModel. And also host the ViewModel outside, in the parent class instance or parent composable and pass just the reference to the composable function
You don't see it in Android perhaps because some mechanics under setContent {} are not causing the App recomposition. Perhaps is more optimized in that sense
k
@Manpreet Kunnath
Copy code
val vm = remember { SomeViewModel() }
add remember!
m
I'll do this and check. I also think it's related to recomposition and remember. Thank you.