Zubair Akber
Zubair Akber

Reputation: 2828

RecyclerView not updating via Live Data Observer

I am trying to update the recyclerView adapter in the observe response of live data object but it is not updating the UI rather if I debug it, it starts updating the UI.

Looks like adding a delay make it work or reassigning the recyclerView items adapter also works but I didn't understand why is the notifyDataSetChanged or notifyItemRangeChanged is not working

following is the code I am using

    adapter = MyAdapter(listOf())
    binding.recyclerView.adapter = adapter


    viewModel = ViewModelProvider(this).get(HomeViewModel::class.java)

    viewModel.data.observe(this, {
        adapter.setData(it)

        // This updates the UI, but this is not the right way to do so 
        //binding.recyclerViewData.adapter = adapter
    })

Adapter class where I update the data

    fun setData(data: MutableList<DataModelRoom>) {
        this.data= data
        notifyItemRangeChanged(0, data.size)
    }

ViewModel part of the code

    var data: MutableLiveData<MutableList<DataModel>> = MutableLiveData()
    

    /* This is part of init method */
    viewModelScope.launch {
        Amplify.Hub.subscribe(HubChannel.DATASTORE) { event ->
            if (event.name == DataStoreChannelEventName.READY.toString()) {
                isAmplifyDataReady.postValue(true)

                data.postValue(repository.getDataFromAmplify())
            }
            Log.i(Logging.TAG_AMPLIFY, "event: $event")
        }

        /* Starting the DataStore Syncing */
        Amplify.DataStore.start(
            { Log.i(Logging.TAG_AMPLIFY, "DataStore started") },
            { Log.e(Logging.TAG_AMPLIFY, "Error starting DataStore", it) }
        )
    }

Layout part of the recyclerView

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="152dp"
    android:orientation="horizontal"
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textViewView" />

Upvotes: 0

Views: 946

Answers (1)

Martin Marconcini
Martin Marconcini

Reputation: 27236

I think you're over complicating the issue. Use a ListAdapter<T, K> (included with the platform and call adapter.submitList(pass_the_new_list_here) and have the (required) DiffUtil.Callback handle the differences and update what's needed.

Upvotes: 1

Related Questions