Search code examples
androidkotlinandroid-recyclerviewindexoutofboundsexceptionkotlin-coroutines

How to avoid IndexOutOfBoundsException when using coroutine asLiveData in a recyclerview List


i am retrieving Flow data from database using .asLiveData(viewModelScope.coroutineContext + Dispatchers.IO) to fill a list that's put in the Recyclerview ListAdapter ... here is my code :

private var getList = { start: Date ->
    getListUseCase(Id!!, start, end!!, query)
        .map {
            it as PagedList
        }.asLiveData(viewModelScope.coroutineContext + Dispatchers.IO)
}

val List: LiveData<PagedList<Type>> =
    Transformations.switchMap(start, getList)

and List is binded to the recyclerview like this :

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycleList"
        adapter="@{adapter}"
        pagedListAdapterData="@{viewModel.List}" />

there is clicks supoose to change start and end and then list is changing , the issue is when clicked on an item so quickly , java.lang.IndexOutOfBoundsException: Index: -1, Size: 9 is caught and the app crashes .

val onItemClicked: (Int) -> Unit = {
    navigate(Navigation.PlanningToDetails(List.value!![it]!!))
}

so how to manage this ? is there a way to block ui thread while the getListUseCase executes on the IO thread ? or is there another solution to make recyclerview unclickable during execution of the usecase ? How would you solve this ?


Solution

  • In order to avoid the exception, you should check the desired index if it is in the range or not.

    val onItemClicked: (Int) -> Unit = {
        if (it >= 0 && it <= List!!.size - 1) {
           navigate(Navigation.PlanningToDetails(List.value!![it]!!))
        }
    }