Caio Costa

06/13/2021, 6:57 PM
Hello folks, how are you doing? Hope you're doing great. So i have these two classes:
Copy code
class MainActivity : AppCompatActivity() {

    private val viewModel: MainViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {

        runTaskOnBackground {
            viewModel.errorStateFlow.collect {
                Toast.makeText(applicationContext, "$it", Toast.LENGTH_LONG).show()

    private fun runTaskOnBackground(task: suspend () -> Unit) =
        addRepeatingJob(Lifecycle.State.CREATED) {


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 K


06/13/2021, 7:17 PM
I can't answer this question in detail but due to specific design decisions (I guess) it is intended that MutableStateFlow expects a default value. What you can do is that you can make the absence of an error message to be part of your state or just use null which suits better in this case

Caio Costa

06/13/2021, 7:29 PM
Got it. Yeah it seems like I'll have to do something along those lines. Thank you Lilly 👍