首页 > 解决方案 > 如何等到一堆电话结束再拨打另一个电话

问题描述

我正在使用RxJava并且我知道concat,我想它确实适合我,因为我想先完成所有第一次通话,然后再进行第二次通话,但我不知道如何实现它。

从现在开始我有这个:

private fun assignAllAnswersToQuestion(questionId: Long) {

        answerListCreated.forEach { assignAnswerToQuestion(questionId, it.id) }

    }

    private fun assignAnswerToQuestion(questionId: Long, answerId: Long) {
        disposable = questionService.addAnswerToQuestion(questionId,answerId,MyUtils.getAccessTokenFromLocalStorage(context = this))
        .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    result -> //Do nothing it should call the next one

                },
                { error -> toast(error.message.toString())}
            )
    }

但是,一旦这一切完成,forEach我想做这样的事情:

private fun assignAllAnswersToQuestion(questionId: Long) {

   answerListCreated.forEach { assignAnswerToQuestion(questionId, it.id) 
   anotherCallHere(questionId) //Do it when the first forEach is finished!!

}

任何想法?

另外,这是一种使用协程的方法吗?

标签: androidkotlinrx-java

解决方案


我想你得把.map你的列表( answerListCreated) 放到一个列表中Flowable,然后Flowable.zip在这个列表上使用。
zip用于将Flowables 的结果组合成一个结果。由于您不需要这些结果,我们将忽略它们。
zip您确定所有之前Flowable的 s 都结束后,您可以.flatMap执行下一个调用(假设anotherCallHere返回一个Flowable.

最后,它将是这样的:

val flowableList = answerListCreated.map { assignAnswerToQuestion(questionId, it.id) }

disposable = Flowable.zip(flowableList) { /* Ignoring results */ }
    .flatMap { anotherCallHere(questionId) }
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe {
        // ...
    }

需要注意的是,如果任何一个调用失败,整个链都会失败(onError将被调用)。


推荐阅读