Hi all, i have working on fragment that observe vi...
# android
n
Hi all, i have working on fragment that observe viewmodel to showing recyclerview, but there is no update when i update the stateflow. Here is the snippet code that i working on, is there any one of you know what is the problem here? On first time recyclerview success showing 15 items, but when add more data there is no update from collect when i debug the code...
Copy code
class SampleViewModel : ViewModel() {
private val _listData = MutableStateFlow<List<PlaceholderContent.PlaceholderItem>>(emptyList())
    val listData = _listData.asStateFlow()

    fun getDataFirstTime() = viewModelScope.launch {
        _listData.value = PlaceholderContent.ITEMS
    }

    fun addMoreData() = viewModelScope.launch {
        PlaceholderContent.addMoreItems(15)
        _listData.value = PlaceholderContent.ITEMS
    }
}
Copy code
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupRecycerview()
        setListenerForNestedScrollTransactions()
        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                launch {
                    vm.listData.collect {
                        adapterSample.setItems(it) // nothing happen here when i execute vm.addMoreData()
                    }
                }
            }
        }

        vm.getDataFirstTime()
    }

private fun setListenerForNestedScrollTransactions() {
    binding.nsvRecyclerview.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { view, _, scrollY, _, oldScrollY ->
        // This line triggered when nestedscrollview hit end of his bottom
        if (shouldLoadMoreData(view, scrollY, oldScrollY)) {
            vm.addMoreData()
        }
    })
}

private fun shouldLoadMoreData(view: NestedScrollView, scrollY: Int, oldScrollY: Int): Boolean {
    return scrollY > oldScrollY && view.getChildAt(0).bottom <= binding.nsvRecyclerview.height + scrollY
}
c
You need to create a new list with a new reference. Passing the same reference will not trigger an update. Also your question is not really Kotlin related. Basic Android question should be asked on a different platform.
🙏 1
n
@Chrimaeon i'm new here and quite confuse about the channel group.. But i think it is related to kotlin. I'm not really know about StateFlow, the documentation not have detail explanation
c
I rather think your issue is with recycler view and the list not getting updated correctly.
Just try with a new instance of the list.
n
actually i have found the answer, i do
Copy code
_listData.update {
    it + newItems
}
👍 2