Using RxJava and Okhttp

前端 未结 5 1887
情书的邮戳
情书的邮戳 2020-12-14 17:15

I want to request to a url using okhttp in another thread (like IO thread) and get Response in the Android main thread, But I don\'t know how to create an

5条回答
  •  失恋的感觉
    2020-12-14 17:31

    I came late to the discussion but, if for some reason the code need to stream the response body, then defer or fromCallable won't do it. Instead one can employ the using operator.

    Single.using(() -> okHttpClient.newCall(okRequest).execute(), // 1
                 response -> { // 2
                     ...
    
                     return Single.just((Consumer) fileOutput -> {
                         try (InputStream upstreamResponseStream = response.body().byteStream();
                              OutputStream fileOutput = responseBodyOutput) {
                             ByteStreams.copy(upstreamResponseStream, output);
                         }
                     });
                 },
                 Response::close, // 3
                 false) // 4
          .subscribeOn(Schedulers.io()) // 5
          .subscribe(copier -> copier.accept(...), // 6
                     throwable -> ...); // 7
    
    1. The first lambda executes the response after upon subscription.
    2. The second lambda creates the observable type, here with Single.just(...)
    3. The third lambda disposes the response. With defer one could have used the try-with-resources style.
    4. Set the eager toggle to false to make the disposer called after the terminal event, i.e. after the subscription consumer has been executed.
    5. Of course make the thing happen on another threadpool
    6. Here's the lambda that will consume the response body. Without eager set to false, the code will raise an IOException with reason 'closed' because the response will be already closed before entering this lambda.
    7. The onError lambda should handle exceptions, especially the IOException that cannot be anymore caught with the using operator as it was possible with a try/catch with defer.

提交回复
热议问题