How to make a HTTP request to check a content type with RxJava 2?

主宰稳场 提交于 2020-01-07 05:43:06

问题


I need to get the content type from a specific URL. I know that we can do it by simply coding:

URL url = new URL("https://someurl.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD"); // Request Method: GET/POST/UPDATE...
connection.connect();
String contentType = connection.getContentType();

Since this blocks the UI thread (a synchronous operation), how to make a HTTP request using RxJava 2 on Android?

Notes:

  • I don't want to make this using the AsyncTask. Why?
  • This is related to RxJava 2 and not version 1.
  • Give me a clear, simple and concise example if you can.

回答1:


Use RxJava just operator to leave main thread and continue the process on thread from computation scheduler and then use flatMap to make http call and find content type, network calls should run on threads from IO scheduler and finally observe on main thread and subscribe to result.

Observable.just(1).subscribeOn(Schedulers.computation())
       .flatMap(dummyValueOne -> {
          return Observable.just(getContentType).subscribeOn(Schedulers.io()); 
       }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String contentType) throws Exception {
            //do nextsteps with contentType, you can even update UI here as it runs on main thread
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Log.e("GetContentType", "exception getting contentType", throwable);
                    }
                }));


来源:https://stackoverflow.com/questions/45381841/how-to-make-a-http-request-to-check-a-content-type-with-rxjava-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!