Caio Costa
06/13/2021, 6:57 PMclass MainActivity : AppCompatActivity() {
private val viewModel: MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
runTaskOnBackground {
viewModel.errorStateFlow.collect {
println("CALLED")
Toast.makeText(applicationContext, "$it", Toast.LENGTH_LONG).show()
}
}
}
private fun runTaskOnBackground(task: suspend () -> Unit) =
addRepeatingJob(Lifecycle.State.CREATED) {
task()
}
}
////////////////////////////////////////////////////
internal class MainViewModel : ViewModel() {
private val _errorStateFlow = MutableStateFlow(0)
val errorStateFlow: StateFlow<Int>
get() = _errorStateFlow
}
The problem i'm getting is that both the Toast and the println i declared are being shown even without posting a value to that MutableStateFlow inside my ViewModel because the value I'm getting is the same as the default one. Looks like the MutableStateFlow is posting the default value automatically. Do you know why this is happening and if there's a way to avoid that? I've searched across the internet but couldn't find someone with the same problem. Thank you in advance KLilly
06/13/2021, 7:17 PMCaio Costa
06/13/2021, 7:29 PM