0

Question

I'm looking to refactor an immutable view state's values in the Android ViewModel (VM) in order to do the following:

  1. Update the view state in the VM cleanly without copying the entire view state
  2. Keep the view state data immutable to the view observing updates

I've built an Android Unidirectional Data Flow (UDF) pattern using LiveData to update the view state changes in the VM that are observed in the view.

See: Android Unidirectional Data Flow with LiveData — 2.0

Full sample code: Coinverse Open App

Implementation

The existing implementation uses nested LiveData.

  • One LiveData val to store the view state in the VM
  • Nested LiveData for the view state attributes as immutable vals
// Stored as viewState LiveData val in VM
data class FeedViewState(
    val contentList: LiveData<PagedList<Content>>
    val anotherAttribute: LiveData<Int>)

The view state is created in the VM's init{...}.

Then, in order to update the view state it must be copied and updated with the given attribute because it is an immutable val. If the attribute were to be mutable, it could be reassigned cleanly without the copy in the VM. However, being immutable is important to make sure the view cannot unintentionally change the val.

class ViewModel: ViewModel() {
    val viewState: LiveData<FeedViewState> get() = _viewState
    private val _viewState = MutableLiveData<FeedViewState>()

    init {
        _viewState.value = FeedViewState(
           contentList = getContentList(...)
           anotherAttribute = ...)
    }

    override fun swipeToRefresh(event: SwipeToRefresh) {
        _viewState.value = _viewState.value?.copy(contentList = getContentList(...))
    }
}

2 Answers 2

1

I am not sure if having "nested LiveData" is okay. When we work with any event-driven design implementation (LiveData, RxJava, Flow) we usually required to assume that the discrete data events are immutable and operations on these events are purely functional. Being immutable is NOT synonymous with being read-only(val). Immutable means immutable. It should be time-invariant and should work exactly the same way under any circumstances. That is one reason why I feel strange to have LiveData or ArrayList members in the data class, regardless of whether they are defined read-only or not.

Another, technical reason why one should avoid nested streams: it is almost impossible to observe them correctly. Every time there is a new data event emitted through the outer stream, the developers must make sure to remove inner subscriptions before observing the new inner stream, otherwise it can cause all sorts of problems. What's the point of having life-cycle aware observers, when the developers need to manually unsubscribe them?

In almost all scenarios, nested streams can be converted to one layer of stream. In your case:

class ViewModel: ViewModel() {

    val contentList: LiveData<PagedList<Content>>
    val anotherAttribute: LiveData<Int>

    private val swipeToRefreshTrigger = MutableLiveData<Boolean>(true)

    init {
        contentList = Transformations.switchMap(swipeToRefreshTrigger) {
            getContentList(...)
        }

        anotherAttribute = ...
    }

    override fun swipeToRefresh(event: SwipeToRefresh) {
        swipeToRefreshTrigger.postValue(true)
    }
}

Notes on PagedList:

PagedList is also mutable, but I guess it is something we just have to live with. PagedList usage is another topic so I won't be discussing it here.

2
  • Thank you for the feedback @SanlokLee! Having the nested LiveData streams does not serve a major benefit in terms of code functionality. To your point, it may cause unintended events. The initial reason for implementing this pattern is to have the view state and view effects organized into their own classes so that it is clear in the view what is being observed. I'll refactor this and share the new pattern above. Feb 10, 2020 at 19:30
  • Take a look at the solution above. The view state LiveData attributes are stored in their own class without the class itself being a LiveData object. This simplifies how values are set and stored. I'm looking forward to your feedback! Please upvote the Q&A if you think it is useful to others. Feb 11, 2020 at 0:56
0

Use Kotlin StateFlow - 7/21/20 Update

Rather than having two state classes with LiveData, one private and mutable, the other public and immutable, with the Kotlin coroutines 1.3.6 release a StateFlow value can be updated in the ViewModel, and rendered in the view's activity/fragment through an interface method.

See: Android Model-View-Intent with Kotlin Flow

Remove Nested LiveData, Create State Classes - 2/11/20

Approach: Store immutable LiveData state and effects in a view state and view effect class inside the ViewModel that is publicly accessible.

The view state and view effects attributes could be LiveData values directly in the VM. However, I'd like to organize the view state and effects into separate classes in order for the view to know whether it observing a view state or a view effect.

class FeedViewState(
        _contentList: MutableLiveData<PagedList<Content>>,
        _anotherAttribute: MutableLiveData<Int>
) {
    val contentList: LiveData<PagedList<Content>> = _contentList
    val anotherAttribute: LiveData<Int> = _anotherAttribute
}

The view state is created in the VM.

class ViewModel: ViewModel() {

    val feedViewState: FeedViewState 
    private val _contentList = MutableLiveData<PagedList<Content>>()
    private val _anotherAttribute = MutableLiveData<Int>()

    init {
        feedViewState = FeedViewState(_contentList, _anotherAttribute)
    }

    ...

    fun updateContent(){
        _contentList.value = ...
    }

    fun updateAnotherAttribute(){
        _anotherAttribute.value = ...
    }
}

Then, the view state attributes would be observed in the activity/fragment.

class Fragment: Fragment() {
    private fun observeViewState() {
        feedViewModel.feedViewState.contentList(viewLifecycleOwner){ pagedList: PagedList<Content> ->
            adapter.submitList(pagedList)
        }
        feedViewModel.feedViewState.anotherAttribute(viewLifecycleOwner){ anotherAttribute: Int ->
            //TODO: Do something with other attribute.
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.