etiennelenhart / Eiffel

Redux-inspired Android architecture library leveraging Architecture Components and Kotlin Coroutines
MIT License
211 stars 14 forks source link

Doubt regarding observing a LiveData Object in State class #124

Closed divyanshunegi closed 4 years ago

divyanshunegi commented 4 years ago
data class StatsFragmentState(
    var viewEvents: StatsFragmentEvents? = null,
    var userProfileModel: LiveData<UserProfileModel>? = null
) : BaseViewState

I have this state class, where BaseViewState has ViewState as parent, in case I need to read the data of userProfileModel do I need to explicitly observer it again? Like this :

        viewModel.observeState(this) {
            it.userProfileModel?.observe(this@StatsFragment, Observer {
                Timber.e("$it")
            })
        }

isnt this put an observer again and again on the live data as many changes happen in viewmodel state ? I might be wrong just need a confirmation from the author.

etiennelenhart commented 4 years ago

LiveData's observe function ignores multiple calls with the same owner, so this technically shouldn't be a problem.

Although I'm curious why you would store a LiveData property inside the ViewState. The state should only contain elements that are directly useable by the view.

If you need to update your ViewState in response to changes of the UserProfileModel first change the property's type to UserProfileModel? instead of the one wrapped with LiveData. Then implement the state property in your ViewModel using a MediatorLiveData and add the LiveData that provides the model's changes with addSource. This gives you a callback where you can update the state with the newest UserProfileModel value.

Hope this answers your question. The upcoming Eiffel 5.0 will make this a lot easier, but will also be a complete rewrite and not backwards compatible. Unfortunately I'm currently way too busy to release it.