当我使用分页库v2和RxJava:时,我正在尝试编写一个Espresso测试
class PageKeyedItemDataSource<T>(
private val schedulerProvider: BaseSchedulerProvider,
private val compositeDisposable: CompositeDisposable,
private val context : Context
) : PageKeyedDataSource<Int, Character>() {
private var isNext = true
private val isNetworkAvailable: Observable<Boolean> =
Observable.fromCallable { context.isNetworkAvailable() }
override fun fetchItems(page: Int): Observable<PeopleWrapper> =
wrapEspressoIdlingResource {
composeObservable { useCase(query, page) }
}
override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, Character>) {
if (isNext) {
_networkState.postValue(NetworkState.LOADING)
isNetworkAvailable.flatMap { fetchItems(it, params.key) }
.subscribe({
_networkState.postValue(NetworkState.LOADED)
//clear retry since last request succeeded
retry = null
if (it.next == null) {
isNext = false
}
callback.onResult(it.wrapper, params.key + 1)
}) {
retry = {
loadAfter(params, callback)
}
initError(it)
}.also { compositeDisposable.add(it) }
}
}
override fun loadInitial(
params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, Character>,
) {
_networkState.postValue(NetworkState.LOADING)
isNetworkAvailable.flatMap { fetchItems(it, 1) }
.subscribe({
_networkState.postValue(NetworkState.LOADED)
if (it.next == null) {
isNext = false
}
callback.onResult(it.wrapper, null, 2)
}) {
retry = {
loadInitial(params, callback)
}
initError(it)
}.also { compositeDisposable.add(it) }
}
}
这是我的wrapEspressoIdlingResource
:
inline fun <T> wrapEspressoIdlingResource(task: () -> Observable<T>): Observable<T> = task()
.doOnSubscribe { EspressoIdlingResource.increment() } // App is busy until further notice
.doFinally { EspressoIdlingResource.decrement() } // Set app as idle.
但它不会等到数据从网络上传输。当我在数据传递之前线程睡眠时,Espresso测试将通过,因此它与我的Idling Resource设置有关。
我相信它可能与分页库有关,因为当我在没有分页库的其他样本中使用Observable类型时,这种方法对它们来说非常适用。
完整的源代码位于:https://github.com/AliRezaeiii/StarWarsSearch-Paging
我错过了什么?
我需要覆盖构建器上的fetchDispatcher:
class BasePageKeyRepository<T>(
private val scheduler: BaseSchedulerProvider,
) : PageKeyRepository<T> {
@MainThread
override fun getItems(): Listing<T> {
val sourceFactory = getSourceFactory()
val rxPagedList = RxPagedListBuilder(sourceFactory, PAGE_SIZE)
.setFetchScheduler(scheduler.io()).buildObservable()
...
}
}