Adapter submitList not adding new items inside LiveData observer

622 views Asked by At

I have the following code that gets info from LiveData from my Room DB -

    private fun initAdapterData() {
        adapter = FriendsListAdapter(requireContext())
        binding.friendsRecyclerview.setAdapterWithItemDecoration(requireContext(), adapter)

//        val testList = mutableListOf<FriendModel>()
//        for (i in 0..15) {
//            testList.add(FriendModel("Alon Shlider", 0))
//        }
//        adapter.submitList(testList)

        viewmodel.getAllFriends().observe(requireActivity(), Observer { userList ->
            val friendsList = mutableListOf<FriendModel>()
            userList.forEach { userModel ->
                friendsList.add(
                    FriendModel(userModel.firstName.plus(" ").plus(userModel.lastName), 0))
            }
            friendsList.forEach {
                Log.d("friend", it.toString())
            }
            lifecycleScope.launch(Dispatchers.Main) {
                adapter.submitList(friendsList)
            }
        })
    }

For some reason, calling submitList inside the observer does not add the items to the list.

I have tried to add fake test items before the observer and it worked, and I have logged the model info before calling my submitList method and it printed valid information.

I also tried to wrap the call to submitList with a coroutine for Main dispacher, thinking it is related to the callback not being in the main thread or something like that but still no result.

What is it that I am missing? everything looks fine but data is not being added to my RecyclerView.

1

There are 1 answers

4
Nensi Kasundra On

First, you have to assign your adapter to RecyclerView and then submit the list.

recylerView.adapter = adapter
adapter.submitList(friendsList)