亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

按順序發出具有不同請求正文的多個 API 請求

按順序發出具有不同請求正文的多個 API 請求

LEATH 2021-09-29 15:30:08
用例:我需要使用 android 客戶端(改造)在服務器中發送一些請求。在我得到第一個答案后,我需要更新發送對象值(取決于我得到的最后一個項目)并重新發送它,直到所有數據都下載完畢。我想知道如何使用 Retrofit 和 RxJava 實現這一點(我不想使用 while 循環等)編輯:問題是,我不知道“平面地圖”的確切數量,因為數據可能會變大或變小。我有 420000 條記錄,對于每個請求,我都下載 1000 條數據
查看完整描述

2 回答

?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

您可以使用flatMap它們,并在下一個中使用它的響應,通過使用it參數,這是前一個的響應。


mathApi.multiplyByTwo(1)

    .flatMap {

        mathApi.multiplyByTwo(it)

    }.flatMap {

        mathApi.multiplyByTwo(it)

    }.subscribe {

        // here "it" will be 4 (1*2*2) 

    }

如果您不知道flatMap最終會有多少個s,例如,您可以使用遞歸函數來完成。


private fun multiplyByTwo(number: Int) {

    mathApi.multiplyByTwo(number).subscribe {

        if (it < Integer.MAX_VALUE) { // When you run out of data.

            multiplyByTwo(it)

        }

    }

}


查看完整回答
反對 回復 2021-09-29
?
牛魔王的故事

TA貢獻1830條經驗 獲得超3個贊

您可以使用保存可變狀態的 generate 函數:


data class ApiResponse(

    val nextPage: Int? = null

)


data class GeneratorState(

    var lastResponse: ApiResponse

)


fun makeApiCall(page: Int): ApiResponse {

    return ApiResponse(page + 1)

}


Flowable

    .generate(

        Callable { GeneratorState(makeApiCall(0)) },

        BiConsumer { state: GeneratorState, emitter: Emitter<ApiResponse> ->

            val latest = state.lastResponse


            if (latest.nextPage != null) {

                val response = makeApiCall(latest.nextPage)

                state.lastResponse = response

                emitter.onNext(response)

            } else {

                emitter.onComplete()

            }

        })

    .subscribe(object : FlowableSubscriber<ApiResponse> {

        var subscription: Subscription? = null


        override fun onSubscribe(s: Subscription) {

            subscription = s

            s.request(1)

        }


        override fun onNext(response: ApiResponse) {

            println("onNext :$response")

            if (response.nextPage != null && response.nextPage < 10) {

                subscription?.request(1)

            } else {

                subscription?.cancel()

            }

        }


        override fun onComplete() {

            println("Completed")

        }


        override fun onError(t: Throwable) {

            t.printStackTrace()

        }

    })


查看完整回答
反對 回復 2021-09-29
  • 2 回答
  • 0 關注
  • 188 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號