CXwudi
07/03/2024, 1:31 AMCXwudi
07/03/2024, 1:36 AMclass CountingStatefulService {
private val _counter: MutableStateFlow<Int> = MutableStateFlow(0)
val counter: StateFlow<Int> = _counter
fun increment() {
_counter.value++
}
}
This class is not even a view model, so the _counter value supposed to reset to 0 when configuration changes happen.
Now I have a very simple `MainActivity`:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
KoinContext(koinApplication {
modules(allModules) // just registered a singleton of CountingStatefulService, nothing else
}.koin) {
MainUI {RootScreen(LocalKoinApplication.current.get())
}
}
}
}
}
Where my UI is just:
@Composable
fun MainUI(
content: @Composable () -> Unit
) {
MaterialTheme {
content()
}
}
@Composable
fun RootScreen(counter: CountingStatefulService, modifier: Modifier = Modifier) {
val count by counter.counter.collectAsState()
Column {
Text("counter = $count")
Button(onClick = { counter.increment() }) {
Text("increment")
}
}
}CXwudi
07/03/2024, 1:40 AMText never reset to counter = 0 when I rotate the screen,
So I am really confused. Does koinApplication in android also did anything to survive configuration changes? If not, then what is causing the _counter value to survive configuration changes?CXwudi
07/03/2024, 2:13 AMonDestroy() to release all resources, then I can see that the _counter will be reset to 0 as expectCaleb Cook
07/04/2024, 12:17 AMCXwudi
07/05/2024, 3:12 AMkoinApplication {} in the onCreate() method in the Activity class, and I didn't even store the koin instance to anywhere, but just passing it to KoinContext {} composable function. Now, I know this is not a good practice as the Koin instance will be re-initialized upon configuration change. But at the same time, I didn't expect the _counter from the example above to survive the configuration change.