androidx.paging.LoadState$NotLoading 无法转换为 androidx.paging.LoadState$Error |分页组合

androidx.paging.LoadState$NotLoading cannot be cast to androidx.paging.LoadState$Error | PagingCompose

事件处理程序

pagingFLow.apply {
    when {
        loadState.refresh is LoadState.Loading -> {}
        loadState.refresh is LoadState.NotLoading -> {}
        loadState.append is LoadState.Loading -> {
            item { CircularProgressIndicator() }
        }
        loadState.refresh is LoadState.Error -> {
            val e = pagingFLow.loadState.append as LoadState.Error
            Log.i("ERROR", e.toString())
        }
        loadState.append is LoadState.Error -> {
            val e = pagingFLow.loadState.append as LoadState.Error
            Log.i("ERROR", e.toString())
        }
    }
}

这里val e = pagingFLow.loadState.append as LoadState.Error抛出androidx.paging.LoadState$NotLoading cannot be cast to androidx.paging.LoadState$Error

这在没有数据库的情况下适用于 DataSource,但是当您添加 RemoteMediator 时它会抛出此错误。

正如 philip dhukov 所暗示的,您正在制作一个不能保证成功的演员阵容

loadState.append 可以是以下任意值:

pagingFLow.apply {
    when {
        ...
        loadState.refresh is LoadState.Error -> {
            val e = pagingFLow.loadState.append as LoadState.Error
            Log.i("ERROR", e.toString())
        }
        ...
    }
}

你实际上可能是指:

pagingFLow.apply {
    when {
        ...
        loadState.append is LoadState.Error -> {
            Log.i("ERROR", loadState.append.toString())
        }
        ...
    }
}

注意:由于智能转换,您不需要在类型检查后显式转换,因此您可以完全省略转换。

此外,通常访问成员是不安全的,并且假设在竞争条件下该值不会改变,因此您应该改用 loadState.member pagingFLow.loadState.member 以防同时调用。虽然这对你的情况可能没问题,但它也会阻止 kotlin 在类型检查后进行智能转换