如何处理KotlinJetpack寻呼3异常?

3z6pesqy  于 2023-02-24  发布在  Kotlin
关注(0)|答案(2)|浏览(136)

我是Kotlin和jetpack的新手,我被要求处理来自pagingdata的错误(异常),我不被允许使用Flow,我只被允许使用LiveData。
这是存储库:

class GitRepoRepository(private val service: GitRepoApi) {

    fun getListData(): LiveData<PagingData<GitRepo>> {
        return Pager(
            // Configuring how data is loaded by adding additional properties to PagingConfig
            config = PagingConfig(
                pageSize = 20,
                enablePlaceholders = false
            ),
            pagingSourceFactory = {
                // Here we are calling the load function of the paging source which is returning a LoadResult
                GitRepoPagingSource(service)
            }
        ).liveData
    }
}

这是视图模型:

class GitRepoViewModel(private val repository: GitRepoRepository) : ViewModel() {

    private val _gitReposList = MutableLiveData<PagingData<GitRepo>>()

    suspend fun getAllGitRepos(): LiveData<PagingData<GitRepo>> {
        val response = repository.getListData().cachedIn(viewModelScope)
        _gitReposList.value = response.value
        return response
    }

}

在我正在进行的活动中:

lifecycleScope.launch {
            gitRepoViewModel.getAllGitRepos().observe(this@PagingActivity, {
                recyclerViewAdapter.submitData(lifecycle, it)
            })
        }

这是我为处理异常而创建的Resource类(如果有,请提供一个更好的类)

data class Resource<out T>(val status: Status, val data: T?, val message: String?) {

    companion object {
        fun <T> success(data: T?): Resource<T> {
            return Resource(Status.SUCCESS, data, null)
        }

        fun <T> error(msg: String, data: T?): Resource<T> {
            return Resource(Status.ERROR, data, msg)
        }

        fun <T> loading(data: T?): Resource<T> {
            return Resource(Status.LOADING, data, null)
        }
    }
}

正如您所看到的,我使用的是协同程序和LiveData。我希望能够在发生异常时将其从仓库或ViewModel返回到Activity,以便在TextView中显示异常或基于异常的消息。

cwtwac6a

cwtwac6a1#

您的GitRepoPagingSource应该捕获可重试的错误,并将它们作为LoadResult.Error(exception)传递给Paging。

class GitRepoPagingSource(..): PagingSource<..>() {
    ...
    override suspend fun load(..): ... {
        try {
            ... // Logic to load data
        } catch (retryableError: IOException) {
            return LoadResult.Error(retryableError)
        }
    }
}

它以LoadState的形式公开给Paging的表示器端,可以通过LoadStateAdapter.addLoadStateListener等以及.retry对其作出React。Paging的所有表示器API都公开这些方法,例如PagingDataAdapterhttps://developer.android.com/reference/kotlin/androidx/paging/PagingDataAdapter

uqdfh47h

uqdfh47h2#

您必须将错误处理程序传递给PagingSource

class MyPagingSource(
    private val api: MyApi,
    private val onError: (Throwable) -> Unit,
): PagingSource<Int, MyModel>() {

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, YourModel> {
        try {
            ...
        } catch(e: Exception) {
            onError(e) // <-- pass your error listener here
        }
    }
}

相关问题