如何使用 RxJava 2 发出 HTTP 请求以检查内容类型? [英] How to make a HTTP request to check a content type with RxJava 2?

查看:55
本文介绍了如何使用 RxJava 2 发出 HTTP 请求以检查内容类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从特定 URL 获取内容类型.我知道我们可以通过简单的编码来实现:

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();

既然这会阻塞 UI 线程(同步操作),那么如何在 Android 上使用 RxJava 2 发出 HTTP 请求?

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

注意事项:

  • 我不想使用 AsyncTask 来实现这一点.为什么?
  • 这与 RxJava 2 而不是版本 1 相关.
  • 如果可以,请给我一个清晰、简单和简洁的示例.

推荐答案

使用 RxJava just operator 离开主线程并从计算调度器继续线程上的进程,然后使用 flatMap 进行 http 调用并查找内容类型,网络调用应该在 IO 调度器的线程上运行,最后在主线程上观察并订阅结果.

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);
                    }
                }));

这篇关于如何使用 RxJava 2 发出 HTTP 请求以检查内容类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆