LiveData Value only observes the last added value but using delay makes it working didn't understand why?

Viewed 199

In my viewmodel class

        class ViewModel(application: Application) : AndroidViewModel(application) {

            private val repository: Repository by lazy {
                Repository.getInstance(getApplication<BaseApplication>().retrofitFactory)
            }

            private var _liveData = MutableLiveData<ItemState>()
            val liveData: LiveData<ItemState> = _liveData


         init {
                fetchData()
            }

            private fun fetchData() {
                repository.getLiveData().observeForever(liveDataObserver)

            }

            override fun onCleared() {
                super.onCleared()
                repository.getLiveData().removeObserver(liveDataObserver)
            }

            private val liveDataObserver = Observer<User> {
                if (it != null) {
                    setData(it)
                }
            }

        private fun setData(it: User) =viewModelScope.launch {
                val list1 = mutableListOf<something1>()
                val list2 = mutableListOf<something2>()

                    list1.add(it.data)
                    list2.add(it.data)
                }
                _liveData.value = ItemState.State1(list1)
                delay(1)
                _liveData.value = ItemState.State2(list2)
            }

The ItemState is a sealed class with two data members

    sealed class ItemState {
            data class State1(val list: List<something1>) : ItemState()
            data class State2(val list: List<something2>) : ItemState()

        }

Activity Observer Code

    viewModel.liveData.observe(this, Observer {
                    loadDataIntoUi(it)
                })

      private fun loadDataIntoUi(data: ItemState) {
                when (data) {
                     is ItemState.State1 -> adaptr1.addItems(data.list)
                     is ItemState.State2 -> adaptr2.addItems(data.list)
        }

Now if i don't use delay in my viewModel here like above the livedata first value that is Office doesn't get observed but it works fine with delay

I have done a lot of research didn't understand why this happening also I have many alternate solutions to this but my question is why delay make's it working

0 Answers
Related