从Rx到协程的分页数据源

问题描述

我想使用Coroutine进行分页功能,我已经在loadInitial()loadAfter()中使用了协程。但是问题是如何将retry()setRetry()setRetry(Action { loadAfter(params,callback) })Rx更改为Coroutine

import androidx.lifecycle.mutablelivedata
import androidx.paging.PageKeyedDataSource
import io.reactivex.Completable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Compositedisposable
import io.reactivex.functions.Action
import io.reactivex.schedulers.Schedulers

class NewsDataSource(
    private val networkService: NetworkService,private val compositedisposable: Compositedisposable)
    : PageKeyedDataSource<Int,News>() {

    var state: mutablelivedata<State> = mutablelivedata()
    private var retryCompletable: Completable? = null


    private val job = Job()
    private val scope = Coroutinescope(IO + job)


    override fun loadInitial(params: LoadInitialParams<Int>,callback: LoadInitialCallback<Int,News>) {
        scope.launch {
            try {
                .....
            }catch (exception : Exception){
                .....
            }
        }
    }

    override fun loadAfter(params: LoadParams<Int>,callback: LoadCallback<Int,News>) {
        scope.launch {
            try {
                .....
            }catch (exception : Exception){
                .....
                setRetry(Action { loadAfter(params,callback) }) // How to change this function from Rx to Coroutine
            }
        }
    }

    override fun loadBefore(params: LoadParams<Int>,News>) {}

    fun retry() { // How to change this function from Rx to Coroutine
        if (retryCompletable != null) {
            compositedisposable.add(retryCompletable!!
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe())
        }
    }

    private fun setRetry(action: Action?) { // How to change this function from Rx to Coroutine
        retryCompletable = if (action == null) null else Completable.fromAction(action)
    }

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)