Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

kotlin - make parallel API calls using RX Android

I have two different endpoints I am using to fetch data for a user. I am using retrofit with the RX Adapter factory. If I make a call to both the endpoints inside a single method sequentially is it considered to be a parallel call executing on two different threads. If not how could I make these API calls parallel using RX? or a way to get the response at the same time while fetching the data in parallel. for example, the first endpoint could take 5 seconds while the second takes 7 seconds but the end response would be available after 7 seconds.

fun fetchData() {
    api.getData()
        .subscribeOn(Schedulers.io())
        .subscribe(
            { profileResponse ->
                //ProfileResponse Object
                Timber.d("profileResponse: $profileResponse")
                //store response for later use
                Cache.save("key", profileResponse.toString())
            },
            {
                Timber.e("error")
            }
        )


    api2.getData()
        .subscribeOn(Schedulers.io())
        .subscribe(
            { profileDetails ->
                //profileDetails Object
                Timber.d("profileDetails: $profileDetails")
            },
            {
                Timber.e("error")
            }
        )
}
question from:https://stackoverflow.com/questions/65916309/make-parallel-api-calls-using-rx-android

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Firstly, you're using subscribeOn() for each observable so it's already executing in parallel.

Is there a way to get the response at the same time while fetching the data in parallel. for example, the first endpoint could take 5 seconds while the second takes 7 seconds but the end response would be available after 7 seconds.

For this, you can use Observable.zip like the following where the time required is the maximum of two calls:

val disposable = Observable.zip(
        firstNetworkCall().subscribeOn(Schedulers.io()),
        secondNetworkCall().subscribeOn(Schedulers.io()),
        BiFunction{
            firstResonse: ResponseOneType,
            secondResponse: ResponseTwoType ->
            combineResult(firstResponse, secondResponse) }))
.observeOn(AndroidSchedulers.mainThread())
        .subscribe { it -> doSomethingWithIndividualResponse(it) }

This article may help to visualize how it's working underneath.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...