MutableStateFlow difference between value and emit

Viewed 4746

What is the difference between using value and emit functions on a MutableStateFlow?

fun main() = runBlocking {

    val mutable = MutableStateFlow(0)

    launch {
        mutable.collect {
            println(it)
        }
    }

    mutable.value = 1
    mutable.emit(2)
}
1 Answers

emit() is a suspend function that wraps a call to set the value:

override suspend fun emit(value: T) {
    this.value = value
}

So the difference is that value lets you set the value even when not in a coroutine. emit() exists so MutableStateFlow can inherit from MutableSharedFlow.

Source code here.

Related