Search code examples
androidkotlinsetterkotlin-stateflow

MutableStateflow Value Vs Update vs Emit


Let say I have a MutableStateFlow variable. What is the main differences and usage of the three cases

mutable.value = 1
mutable.emit(2)
mutable.update {3}

Solution

  • emit() is nothing but a suspend function which internally uses the mutable.value = newValue.

    The update {} is used for atomic updates i.e. for managing/handling concurrent operations which internally uses compareAndSet to (obviously) compare the values & see if the previous value has changed or not (say via some other Thread).

    You can read more about update {} here:
    https://medium.com/geekculture/atomic-updates-with-mutablestateflow-dc0331724405