在 recyclerview 列表中使用协程 asLiveData 时如何避免 IndexOutOfBoundsException

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

我正在使用 .asLiveData(viewModelScope.coroutineContext + Dispatchers.IO) 从数据库中检索流数据,以填充放入 Recyclerview ListAdapter 中的列表...这是我的代码:

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)

List 像这样绑定到 recyclerview :

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

点击 supoose 更改开始和结束,然后列表发生变化,问题是当点击一个项目时,所以 quickly,java.lang.IndexOutOfBoundsException:索引:-1,大小: 9 被捕获,应用程序崩溃。

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

那么如何管理呢?有没有办法在 getListUseCase 在 IO 线程上执行时阻止 ui 线程?或者是否有另一种解决方案可以在用例执行期间使 recyclerview 不可点击? 你会如何解决这个问题?

为了避免异常,您应该检查所需的索引是否在范围内。

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