Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MutableStateFlow difference between value and emit

What is the difference between using value end emit fun on a MutableStateFlow?

fun main() = runBlocking {

    val mutable = MutableStateFlow(0)

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

    mutable.value = 1
    mutable.emit(2)
}
like image 938
appersiano Avatar asked Mar 17 '21 08:03

appersiano


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.

like image 100
Tenfour04 Avatar answered Oct 08 '22 06:10

Tenfour04