In my Android app, with Kotlin and using Koin dependency injection, my init block is repeatedly called every time the app is brought into the foreground. The issue this causes is making additional background calls that are not necessary when the app is brought into the foreground, and the View refreshes when I don't always want it too. My question is, how to properly utilize the init block and collect a single flow without the init block methods being repeatedly called? Is init { } always called when a ViewModel is brought into the foreground?
Below is an example of how I'm utilizing the ViewModel in my fragment, and the methods called in my init block:
import org.koin.androidx.viewmodel.ext.android.*
class MyFragment: Fragment() {
private val viewModel: MyViewModel by viewModel()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
collectSomeFlow()
}
private fun collectSomeFlow() {
lifecycleScope.launchWhenStarted {
viewModel.onUiStateChanged.collect {
// do something here
}
}
}
}
class MyViewModel: ViewModel(private val repository: MyRepository): ViewModel() {
private val _uiState: MutableStateFlow<MyUiState> = MutableStateFlow(MyUiState.Success(emptyList()))
val uiState: StateFlow<MyUiState> = _uiState
init {
// Repeatedly fired off after View is created if app is resumed again
getSomeDataFromNetwork()
}
private fun getSomeDataFromNetwork() {
viewModelScope.launch {
val response = repository.getSomeDataFromNetwork()
// Handle response, update _uiState, etc.
}
}
}