Search code examples
androidkotlinmvvmandroid-viewpagerandroid-livedata

ViewPager2 with ListAdapter (from android) shows java.lang.IllegalStateException


When I am using androidx ListAdapter with ViewPager2 and try to update the specific list item from fragment with adapter.notifyItemChanged, I have crash that shows java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling.

Previously I was using recyclerView and could resolve the crash by the condition with if(recyclerView.isComputingLayout()) before adapter.notifyItemChanged. Unfortunately ViewPager does not have method that returns computing information. Also, checking the stateScroll gives me nothing. Maybe someone had this problem before? Here's code:

viewModel.invoicePositionList.observe(viewLifecycleOwner, {
        if (viewModel.currentInvoicePositionPosition >= 0) {
            adapter.notifyItemChanged(viewModel.currentInvoicePositionPosition)
            viewModel.currentInvoicePositionPosition = -1
        } else {
            adapter.submitList(it)
        }
    })

Solution

  • You are not expected to call notifyItemChanged when using ListAdapter. All you need is to create a new list without the removed item and call submitList.