Why do the author need to use asStateFlow() in Compose?

Viewed 397

The Code A is a sample code from the video.

I can't understand why the author need to use asStateFlow().

I think the Code B is OK, right?

Code A

class MainViewModel: ViewModel() {
    private val _stateFlow= MutableStateFlow("Hello World")
    val stateFlow = _stateFlow.asStateFlow()
    ...
}

Code B

class MainViewModel: ViewModel() {
    private val _stateFlow= MutableStateFlow("Hello World")
    val stateFlow = _stateFlow
    ...
}
    
1 Answers

Code A makes the stateFlow read-only while Code B exposes the mutable state flow as is.

The documentation of asStateFlow() is pretty clear about this:

Represents this mutable state flow as a read-only state flow.

If you take a look at the implemenation, you can see that it wraps the current (mutable) flow in a ReadonlyStateFlow which is, well, read-only:

public fun <T> MutableStateFlow<T>.asStateFlow(): StateFlow<T> =
    ReadonlyStateFlow(this, null)

To make it easier to understand, if you use MainViewModel in a component, this outsider will be able to read the values but not write them in case of Code A. Meanwhile, if you use Code B, the outsider component may emit its own values to the state flow. This is usually undesirable as it should be the ViewModel's responsibility to emit data (this is called unidirectional data flow) as a response to actions coming from the observers (the view components).

Related