Pablo
08/20/2024, 6:08 PMobject customSingleton {
var customVar = "Hello World"
}
How can that be observed in a viewmodel?Michael Krussel
08/20/2024, 6:10 PMPablo
08/20/2024, 6:12 PMMichael Krussel
08/20/2024, 6:15 PMStateFlow
. But general way, would be to have a private MutableStateFlow
, make the customVar
getter and setter use the value from MutableStateFlow
and then expose another property of type StateFlow
that can be collected. Then in the view model, collect the state flow in a job launched from the view model's scope.Pablo
08/20/2024, 6:23 PMPablo
08/20/2024, 6:23 PMPablo
08/20/2024, 6:24 PMval currentScreenId = MutableStateFlow<Int>(CustomSingleton.customVar)
val currentScreenIdState: StateFlow<Int> = currentScreenId.stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5_000),
CustomSingleton.customVar
)
Pablo
08/20/2024, 6:24 PMCustomSingleton.customVar
in these two places? When I update the variable on the singleton will the composables listeing for this stateflow be recreated?Pablo
08/20/2024, 6:46 PMCustomSingleton.customVar = 1
), the composable is not being recomposedPablo
08/20/2024, 6:47 PMval currentSectionId by viewModel.currentScreenIdState.collectAsStateWithLifecycle()
Michael Krussel
08/20/2024, 8:16 PMCustomSingleton
.
object CustomSingleton {
private val _customVarFlow = MutableStateFlow("Hello World")
val customVarFlow = _customVarFlow.asStateFlow()
var customVar: String
get() = _customVarFlow.value
set(value) {
_customVarFlow.value = value
}
}
class MyViewModel: ViewModel() {
init {
viewModelScope.launch {
CustomSingleton.customVarFlow.collect { currentVal ->
// do something
}
}
}
}
Pablo
08/20/2024, 8:31 PMMichael Krussel
08/20/2024, 8:35 PMcollectAsStateWithLifecycle
is an option. You asked about the view model listening to it. So it all depends on what you are doing with it.