Home > Back-end >  How to call multiple requests with okhttpclient and RxJava but without retrofit
How to call multiple requests with okhttpclient and RxJava but without retrofit

Time:12-24

I have a list of URLs that I need to call and if I got success response for all of them, I can continue.

I can simply do it with RxJava and Retrofit like:

@PUT
fun uploadFile(@Url url: String, @Body file: RequestBody): Single<Response<Void>>


Observable.fromIterable(uploadUrls)
    .flatMapSingle {
        val requestBody = InputStreamRequestBody(contentResolver, uri)
        upsellServiceApi.uploadFile(url, requestBody)
    }
    .toList()
    .subscribeOn(schedulerProvider.io())
    .observeOn(schedulerProvider.ui())
    .subscribe(
        { responses ->
            if (responses.all { it.isSuccessful }) {
                // continue
            } else {
               //error
            }
        },
        {
            // error
        }

Now I need to do the same thing without retrofit and by only using okhttpclient. How should I do it?

CodePudding user response:

You could use a library like https://github.com/liujingxing/rxhttp to keep using RxJava. Or implement it yourself Using RxJava and Okhttp

If you don't want to use RxJava, then just enqueue and handle callback methods yourself.

CodePudding user response:

Solved it

Observable.fromIterable(uploadUrls)
    .map {
        val request = Request.Builder().url(url).put(InputStreamRequestBody(contentResolver!!, uri)).build()
        okHttpClient.newCall(request).execute()
    }
    .collect(
        {
            mutableListOf<Response>()
        },
        {
                list: MutableList<Response>, response: Response -> list.add(response)
        }
    )
    .subscribeOn(schedulerProvider.io())
    .observeOn(schedulerProvider.ui())
    .subscribe(
        { responses ->
            if (responses.all { it.isSuccessful }) {
                // continue
            } else {
                // error
            }
        },
        {
            // error
        }
    ).also { compositeDisposable.add(it) }
  • Related