just_user
just_user

Reputation: 12059

Android StateFlow or MutableStateFlow in data binding

I'm trying out StateFlow in DataBindings and in all examples I can find, most look like a copy of this one, two variables are used in the ViewModel for one data binding. One private MutableStateFlow and a public StateFlow. And the StateFlow is pretty much just reading the value from the MutableStateFlow. Why is this? Wouldn't it be easier to just have one variable, a MutableStateFlow and skip the StateFlow variable all together?

Upvotes: 2

Views: 3986

Answers (1)

Henry Twist
Henry Twist

Reputation: 5980

This is just a simple case of encapsulation (and is unrelated to data binding/Android). From a technical standpoint, this is a redundant step and doesn't make a difference. From a design standpoint however, it restricts modification of the StateFlow value outside of your containing class.

This is quite a common pattern with 'observable data holders' (MutableLiveData and LiveData), which can be thought as similar to having a property with a private setter. In fact, if you only need to collect the flow and not access its value, you could even use Flow as the exposed type (although as @MarkKeen pointed out, this won't work with data binding).

Upvotes: 6

Related Questions