Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 728|回复: 0

[默认分类] RxJava 的使用入门

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2018-7-13 16:57:14 | 显示全部楼层 |阅读模式
    一、什么是 Rxjava
    RxJava 是一个响应式编程框架,采用观察者设计模式。所以自然少不了 Observable 和 Subscriber 这两个东东了。
    RxJava 是一个开源项目,地址:https://github.com/ReactiveX/RxJava

    还有一个RxAndroid,用于 Android 开发,添加了 Android 用的接口。地址:https://github.com/ReactiveX/RxAndroid
    二、例子
    通过请求openweathermap 的天气查询接口返回天气数据
    1、增加编译依赖

    1. 1 dependencies {
    2. 2     compile fileTree(dir: "libs", include: ["*.jar"])
    3. 3     compile "com.android.support:appcompat-v7:22.0.0"
    4. 4     compile "io.reactivex:rxjava:1.0.9"
    5. 5     compile "io.reactivex:rxandroid:0.24.0"
    6. 6     compile "com.squareup.retrofit:retrofit:1.9.0"
    7. 7 }
    复制代码

    retrofit 是一个 restful 请求客户端。详见:http://square.github.io/retrofit/
    2、服务器接口

    1. 1 /**
    2. 2  * 接口
    3. 3  * Created by Hal on 15/4/26.
    4. 4  */
    5. 5 public class ApiManager {
    6. 6
    7. 7     private static final String ENDPOINT = "http://api.openweathermap.org/data/2.5";
    8. 8
    9. 9     /**
    10. 10      * 服务接口
    11. 11      */
    12. 12     private interface ApiManagerService {
    13. 13         @GET("/weather")
    14. 14         WeatherData getWeather(@Query("q") String place, @Query("units") String units);
    15. 15     }
    16. 16
    17. 17     private static final RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(ENDPOINT).setLogLevel(RestAdapter.LogLevel.FULL).build();
    18. 18
    19. 19     private static final ApiManagerService apiManager = restAdapter.create(ApiManagerService.class);
    20. 20
    21. 21     /**
    22. 22      * 将服务接口返回的数据,封装成{@link rx.Observable}
    23. 23      * @param city
    24. 24      * @return
    25. 25      */
    26. 26     public static Observable<WeatherData> getWeatherData(final String city) {
    27. 27         return Observable.create(new Observable.OnSubscribe<WeatherData>() {
    28. 28             @Override
    29. 29             public void call(Subscriber<? super WeatherData> subscriber) {
    30. 30                 //订阅者回调 onNext 和 onCompleted
    31. 31                 subscriber.onNext(apiManager.getWeather(city, "metric"));
    32. 32                 subscriber.onCompleted();
    33. 33             }
    34. 34         }).subscribeOn(Schedulers.io());
    35. 35     }
    36. 36 }
    复制代码

    订阅者的回调有三个方法,onNext,onError,onCompleted
    3、接口调用

    1. 1   /**
    2. 2          * 多个 city 请求
    3. 3          * map,flatMap 对 Observable进行变换
    4. 4          */
    5. 5         Observable.from(CITIES).flatMap(new Func1<String, Observable<WeatherData>>() {
    6. 6             @Override
    7. 7             public Observable<WeatherData> call(String s) {
    8. 8                 return ApiManager.getWeatherData(s);
    9. 9             }
    10. 10         }).subscribeOn(Schedulers.io())
    11. 11                 .observeOn(AndroidSchedulers.mainThread())
    12. 12                 .subscribe(/*onNext*/new Action1<WeatherData>() {
    13. 13                     @Override
    14. 14                     public void call(WeatherData weatherData) {
    15. 15                         Log.d(LOG_TAG, weatherData.toString());
    16. 16                     }
    17. 17                 }, /*onError*/new Action1<Throwable>() {
    18. 18                     @Override
    19. 19                     public void call(Throwable throwable) {
    20. 20
    21. 21                     }
    22. 22                 });
    23. 23
    24. 24         /**
    25. 25          * 单个 city 请求
    26. 26          */
    27. 27         ApiManager.getWeatherData(CITIES[0]).subscribeOn(Schedulers.io())
    28. 28                 .observeOn(AndroidSchedulers.mainThread())
    29. 29                 .subscribe(new Action1<WeatherData>() {
    30. 30                     @Override
    31. 31                     public void call(WeatherData weatherData) {
    32. 32                         Log.d(LOG_TAG, weatherData.toString());
    33. 33                         ((TextView) findViewById(R.id.text)).setText(weatherData.toString());
    34. 34                     }
    35. 35                 }, new Action1<Throwable>() {
    36. 36                     @Override
    37. 37                     public void call(Throwable throwable) {
    38. 38                         Log.e(LOG_TAG, throwable.getMessage(), throwable);
    39. 39                     }
    40. 40                 });
    41. 41
    42. 42         /**
    43. 43          * Android View 事件处理
    44. 44          */
    45. 45         ViewObservable.clicks(findViewById(R.id.text), false).subscribe(new Action1<OnClickEvent>() {
    46. 46             @Override
    47. 47             public void call(OnClickEvent onClickEvent) {
    48. 48
    49. 49             }
    50. 50         });
    复制代码

    subscribeOn(Schedulers.io())observeOn(AndroidSchedulers.mainThread())分别定义了这两个动作的线程。Android UI 更新需要在主线程。
    4、retrofit 支持 rxjava 整合

    1. 1 /**
    2. 2      * 服务接口
    3. 3      */
    4. 4     private interface ApiManagerService {
    5. 5         @GET("/weather")
    6. 6         WeatherData getWeather(@Query("q") String place, @Query("units") String units);
    7. 7
    8. 8         /**
    9. 9          * retrofit 支持 rxjava 整合
    10. 10          * 这种方法适用于新接口
    11. 11          */
    12. 12         @GET("/weather")
    13. 13         Observable<WeatherData> getWeatherData(@Query("q") String place, @Query("units") String units);
    14. 14     }
    复制代码

    Demo 代码

    --------EOF-----
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-4-19 14:08 , Processed in 0.371969 second(s), 46 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表