Day23-RxJava&Retrofit

RxJava

组成

1. 上游 Observable

2. 下游 多种

无参的subscribe()表示下游不关心数据类型
带Cunsumer的表示下游只关心 onNext, 其他的装没看见

* public final Disposable subscribe() {}
* public final Disposable subscribe(Consumer<? super T> onNext) {}
* public final Disposable subscribe(Consumer<? super T> onNext, Consumer<? super Throwable> onError) {}
* public final Disposable subscribe(Consumer<? super T> onNext, Consumer<? super Throwable> onError, Action onComplete) {}
* public final Disposable subscribe(Consumer<? super T> onNext, Consumer<? super Throwable> onError, Action onComplete, Consumer<? super Disposable> onSubscribe) {}
* public final void subscribe(Observer<? super T> observer) {}

上有和下游之间可以添加各种参数

3. 水管 subscribe

4. 指定上游线程 subscribeOn()

多次指定上游线程, 只有第一次有效

5. 指定下游线程 observeOn()

下游线程可以多次指定

RxJava提供的线程
  • Schedulers.io(), 代表io操作线程, 通常用于网络/读写等密集型操作
  • Schedulers.computation, 代表CPu密集型计算
  • Schedulers.newThread(), 代表一个常规的新线程
  • AndroidSchedulers.mainThread(), 代表Android的主线程
    RxJava内部使用线程池来维护, 所以效率也比较高

AndroidSchedulers.mainThread()是RxAndroid包里的

6.变换操作符

Map

截获事件水流

FlatMap

比Map更复杂, 将上游的Observable转化成多个Observable, 然后将他们发射的事件合并后放进一个单独的Observable里, 但是不保证事件顺序

concatMap

保证事件顺序的 FlatMap

实践

Retrofit连续请求

分为两个请求, 第一个请求, 根据经纬度向百度请求, 拿到转换出的城市名, 第二个请求, 请求和风天气, 将城市名转换成城市名对应的天气

  1. 准备好百度地图的城市json对应的bean
public class LocationEntity {

    /**
     * status : OK
     * result : {"location":{"lng":121.490523,"lat":31.407452},"formatted_address":"上海市宝山区牡丹江路1599号","business":"友谊路,北翼商业街,吴淞","addressComponent":{"city":"上海市","direction":"near","distance":"0","district":"宝山区","province":"上海市","street":"牡丹江路","street_number":"1599号"},"cityCode":289}
     */

    private String status;
    private ResultBean result;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public ResultBean getResult() {
        return result;
    }

    public void setResult(ResultBean result) {
        this.result = result;
    }

    public static class ResultBean {
        /**
         * location : {"lng":121.490523,"lat":31.407452}
         * formatted_address : 上海市宝山区牡丹江路1599号
         * business : 友谊路,北翼商业街,吴淞
         * addressComponent : {"city":"上海市","direction":"near","distance":"0","district":"宝山区","province":"上海市","street":"牡丹江路","street_number":"1599号"}
         * cityCode : 289
         */

        private LocationBean location;
        private String formatted_address;
        private String business;
        private AddressComponentBean addressComponent;
        private int cityCode;

        public LocationBean getLocation() {
            return location;
        }

        public void setLocation(LocationBean location) {
            this.location = location;
        }

        public String getFormatted_address() {
            return formatted_address;
        }

        public void setFormatted_address(String formatted_address) {
            this.formatted_address = formatted_address;
        }

        public String getBusiness() {
            return business;
        }

        public void setBusiness(String business) {
            this.business = business;
        }

        public AddressComponentBean getAddressComponent() {
            return addressComponent;
        }

        public void setAddressComponent(AddressComponentBean addressComponent) {
            this.addressComponent = addressComponent;
        }

        public int getCityCode() {
            return cityCode;
        }

        public void setCityCode(int cityCode) {
            this.cityCode = cityCode;
        }

        public static class LocationBean {
            /**
             * lng : 121.490523
             * lat : 31.407452
             */

            private double lng;
            private double lat;

            public double getLng() {
                return lng;
            }

            public void setLng(double lng) {
                this.lng = lng;
            }

            public double getLat() {
                return lat;
            }

            public void setLat(double lat) {
                this.lat = lat;
            }
        }

        public static class AddressComponentBean {
            /**
             * city : 上海市
             * direction : near
             * distance : 0
             * district : 宝山区
             * province : 上海市
             * street : 牡丹江路
             * street_number : 1599号
             */

            private String city;
            private String direction;
            private String distance;
            private String district;
            private String province;
            private String street;
            private String street_number;

            public String getCity() {
                return city;
            }

            public void setCity(String city) {
                this.city = city;
            }

            public String getDirection() {
                return direction;
            }

            public void setDirection(String direction) {
                this.direction = direction;
            }

            public String getDistance() {
                return distance;
            }

            public void setDistance(String distance) {
                this.distance = distance;
            }

            public String getDistrict() {
                return district;
            }

            public void setDistrict(String district) {
                this.district = district;
            }

            public String getProvince() {
                return province;
            }

            public void setProvince(String province) {
                this.province = province;
            }

            public String getStreet() {
                return street;
            }

            public void setStreet(String street) {
                this.street = street;
            }

            public String getStreet_number() {
                return street_number;
            }

            public void setStreet_number(String street_number) {
                this.street_number = street_number;
            }
        }
    }
}
  1. 准备 Rxjava 的 interface
public interface Api {

    @GET("weather")
    Observable<Weather2> getWeatherRx(
            @Query("city")String city,
            @Query("key")String key);

    @GET("geocoder")
    Observable<LocationEntity> getLoation(
            @Query("location") String location,
            @Query("output") String output,
            @Query("key") String key
    );
}
  1. 创建Retrofit
public class RetrofitCreater {

    public static Retrofit createWeather() {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder.readTimeout(10, TimeUnit.SECONDS);
        builder.connectTimeout(9, TimeUnit.SECONDS);
        builder.retryOnConnectionFailure(true);//错误时重复请求
        builder.connectTimeout(15, TimeUnit.SECONDS);

        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLogger());
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addNetworkInterceptor(interceptor);
        }

        return new Retrofit.Builder().baseUrl("https://free-api.heweather.com/v5/")
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    public static Retrofit createLoc() {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder.readTimeout(10, TimeUnit.SECONDS);
        builder.connectTimeout(9, TimeUnit.SECONDS);
        builder.retryOnConnectionFailure(true);//错误时重复请求
        builder.connectTimeout(15, TimeUnit.SECONDS);

        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLogger());
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addNetworkInterceptor(interceptor);
        }

        return new Retrofit.Builder().baseUrl("http://api.map.baidu.com/")
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }
}
  1. 调用Retrofit
private void requestRxLocation() {
    Retrofit weatherRetrofit = RetrofitCreater.createWeather();
    final Api weatherApi = weatherRetrofit.create(Api.class);
    final Retrofit retrofitLoc = RetrofitCreater.createLoc();
    Api locApi = retrofitLoc.create(Api.class);
    locApi.getLoation("39.90400,116.39100", "json", "6eea93095ae93db2c77be9ac910ff311")
            .flatMap(new Function<LocationEntity, ObservableSource<Weather2>>() {
                @Override
                public ObservableSource<Weather2> apply(LocationEntity locationEntity) throws Exception {
                    Log.i(tag, locationEntity.getResult().getAddressComponent().getCity()+"");
                    return weatherApi.getWeatherRx(locationEntity.getResult().getAddressComponent().getCity(), "你的和风天气key"); //拿到城市名, 开始请求天气接口
                }
            }).map(new Function<Weather2, String>() {
                @Override
                public String apply(Weather2 weather2) throws Exception {
                    String text = weather2.getHeWeather5().get(0).getBasic().getCity();
                    return text;
                }
            }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<String>() {
                @Override
                public void accept(String s) throws Exception {
                    Log.i(tag,"accept"+s);
                }
            });


}

database

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,386评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,142评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,704评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,702评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,716评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,573评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,314评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,230评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,680评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,873评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,991评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,706评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,329评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,910评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,038评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,158评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,941评论 2 355

推荐阅读更多精彩内容

  • 转载自:https://xiaobailong24.me/2017/03/18/Android-RxJava2.x...
    Young1657阅读 2,022评论 1 9
  • 我从去年开始使用 RxJava ,到现在一年多了。今年加入了 Flipboard 后,看到 Flipboard 的...
    Jason_andy阅读 5,473评论 7 62
  • 怎么如此平静, 感觉像是走错了片场.为什么呢, 因为上下游工作在同一个线程呀骚年们! 这个时候上游每次调用emit...
    Young1657阅读 1,466评论 2 1
  • 前言我从去年开始使用 RxJava ,到现在一年多了。今年加入了 Flipboard 后,看到 Flipboard...
    占导zqq阅读 9,164评论 6 151
  • 2.17.4.12 星期三 累计73 一、目标: 本期目标实现财富收入50万元。通过我的目标实现,希望能帮助更多...
    鹊曾阅读 177评论 0 0