如何在kotlin/java中对同一方法调用进行排队

sxissh06  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(349)

我使用diffutil计算recyclerview中的数据更改。计算是在调度程序线程上使用rxjava异步完成的,如下所示:

fun setResultItems(list: List<FlightResultItem>?) {
    Log.d("debugfilter", "            setResultItems of size: " + (list?.size?: 0))
    list?.let { newList ->
        Single.fromCallable { DiffUtil.calculateDiff(ResultItemDiffUtilCallback(ArrayList(newList), ArrayList(resultItems))) }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { diffResult ->
                    Log.d("debugfilter", "            setResultItems AFTER DIFF of size: " + (newList.size))
                    resultItems = ArrayList(newList)
                    diffResult.dispatchUpdatesTo(this)

                }.also { mCompositeSubscription?.add(it) }
    }
}

当函数连续调用时,大数据集的计算将最后完成

D: debugfilter : setResultItems of size: 113 
D: debugfilter : setResultItems of size: 7 
D: debugfilter : setResultItems AFTER DIFF of size: 7 
D: debugfilter : setResultItems AFTER DIFF of size: 113

有没有办法将方法调用排队,等待执行完成,然后再执行另一个方法调用?

vngu2lb8

vngu2lb81#

我认为可以使用scheduler.single()创建单线程工作线程。它将按顺序处理请求。

fun setResultItems(list: List<FlightResultItem>?) {
Log.d("debugfilter", "            setResultItems of size: " + (list?.size?: 0))
list?.let { newList ->
    Single.fromCallable { DiffUtil.calculateDiff(ResultItemDiffUtilCallback(ArrayList(newList), ArrayList(resultItems))) }
        .subscribeOn(Schedulers.single())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe { diffResult ->
            Log.d("debugfilter", "            setResultItems AFTER DIFF of size: " + (newList.size))
            resultItems = ArrayList(newList)
            diffResult.dispatchUpdatesTo(this)

        }.also { mCompositeSubscription?.add(it) }
}
}

相关问题