Nicolas Manurung
07/12/2023, 9:25 AMclass 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
}
}
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
}
Chrimaeon
07/12/2023, 9:31 AMNicolas Manurung
07/12/2023, 11:26 AMChrimaeon
07/12/2023, 11:28 AMChrimaeon
07/12/2023, 11:29 AMNicolas Manurung
07/12/2023, 11:30 AM_listData.update {
it + newItems
}