美文网首页
小试牛刀RxJava2之首页检查

小试牛刀RxJava2之首页检查

作者: 小范屯 | 来源:发表于2017-01-14 16:42 被阅读126次

    前言

    当我第一次听说RxJava是在2015年的11月,掐指一算距今过去了1年多了,现在RxJava2都发布了。现在公司项目的的业务需要,有一块逻辑涉及到子线程和主线程的来回切换。如果使用传统的Thread+Handler的写法,写出来的代码就跳来跳去,还有可能出现多次嵌套。很利于阅读理解里面的逻辑和后期的维护开发。早就听说RxJava的大名,通过响应式编程很好的处理异步问题。这次正好有这个机会,自己就动手实践一下。


    Screen Shot 2017-01-14 at 18.27.50.png

    产品流程

    只有前一个执行完成(不管是否成功),才能执行后面一个。

    1. 新手引导
    2. 检查升级
    3. 弹窗视图

    一张图你就懂了


    ezgif.com-video-to-gif.gif

    开发流程

    1. 检查sp里的isFirst-子线程
    2. 显示带动画的引导界面-主线程
    3. 监听动画结束-主线程
    4. 监听引导界面的点击事件-主线程
    5. 隐藏带动画的引导界-主线程
    6. 监听动画结束-主线程
    7. 将sp里的isFirst置为false-子线程
    8. 发起检查版本请求-子线程
    9. 显示版本更新的dialog-主线程
    10. 监听对话框消失-主线程
    11. 发起获取弹窗数据的请求-子线程
    12. 显示弹窗视图-主线程
    //TODO rxpreference 发送两次
    Disposable disposable = Observable
            //返回:是否为第一次安装
            .create(new ObservableOnSubscribe<Boolean>() {
                @Override
                public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
                    e.onNext(PreferenceManager
                            .getDefaultSharedPreferences(context)
                            .getBoolean("isFirst", true));
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            //返回:是否为第一次安装
            .flatMap(new Function<Boolean, ObservableSource<Boolean>>() {
                @Override
                public ObservableSource<Boolean> apply(Boolean aBoolean) throws Exception {
                    if (aBoolean) {
                        return Observable.create(new ObservableOnSubscribe<Boolean>() {
                            @Override
                            public void subscribe(final ObservableEmitter<Boolean> e) throws Exception {
                                AlphaAnimation alphaAnimation = new AlphaAnimation(0.1f, 1.0f);
                                alphaAnimation.setDuration(2000);
                                alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
                                    @Override
                                    public void onAnimationStart(Animation animation) {
    
                                    }
    
                                    @Override
                                    public void onAnimationEnd(Animation animation) {
                                        if (!e.isDisposed()) {
                                            e.onNext(true);
                                        }
                                    }
    
                                    @Override
                                    public void onAnimationRepeat(Animation animation) {
    
                                    }
                                });
                                fragment_home_guide.setVisibility(View.VISIBLE);
                                fragment_home_guide.startAnimation(alphaAnimation);
                            }
                        });
                    } else {
                        return Observable.create(new ObservableOnSubscribe<Boolean>() {
                            @Override
                            public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
                                e.onNext(false);
                            }
                        });
                    }
                }
            })
            //返回:是否为第一次安装
            .flatMap(new Function<Boolean, ObservableSource<Boolean>>() {
                @Override
                public ObservableSource<Boolean> apply(Boolean aBoolean) throws Exception {
                    if (aBoolean) {
                        return Observable.create(new ObservableOnSubscribe<Boolean>() {
                            @Override
                            public void subscribe(final ObservableEmitter<Boolean> e) throws Exception {
                                fragment_home_guide.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        if (!e.isDisposed()) {
                                            e.onNext(true);
                                        }
                                    }
                                });
                                e.setDisposable(new Disposable() {
                                    @Override
                                    public void dispose() {
                                        fragment_home_guide.setOnClickListener(null);
                                    }
    
                                    @Override
                                    public boolean isDisposed() {
                                        return true;
                                    }
                                });
    //                                e.add(new MainThreadSubscription() {
    //                                    @Override
    //                                    protected void onUnsubscribe() {
    //                                        fragment_home_guide.setOnClickListener(null);
    //                                    }
    //                                });
                            }
                        });
                    } else {
                        return Observable.create(new ObservableOnSubscribe<Boolean>() {
                            @Override
                            public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
                                e.onNext(false);
                            }
                        });
                    }
                }
            })
            //返回:是否为第一次安装
            .flatMap(new Function<Boolean, ObservableSource<Boolean>>() {
                @Override
                public ObservableSource<Boolean> apply(Boolean aBoolean) throws Exception {
                    if (aBoolean) {
                        return Observable.create(new ObservableOnSubscribe<Boolean>() {
                            @Override
                            public void subscribe(final ObservableEmitter<Boolean> e) throws Exception {
                                AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.1f);
                                alphaAnimation.setDuration(2000);
                                alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
                                    @Override
                                    public void onAnimationStart(Animation animation) {
    
                                    }
    
                                    @Override
                                    public void onAnimationEnd(Animation animation) {
                                        if (!e.isDisposed()) {
                                            e.onNext(true);
                                        }
                                    }
    
                                    @Override
                                    public void onAnimationRepeat(Animation animation) {
    
                                    }
                                });
                                fragment_home_guide.setVisibility(View.GONE);
                                fragment_home_guide.startAnimation(alphaAnimation);
                            }
                        });
                    } else {
                        return Observable.create(new ObservableOnSubscribe<Boolean>() {
                            @Override
                            public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
                                e.onNext(false);
                            }
                        });
                    }
                }
            })
            .observeOn(Schedulers.io())
            //返回:是否为第一次安装
            .map(new Function<Boolean, Boolean>() {
                @Override
                public Boolean apply(Boolean aBoolean) throws Exception {
                    if (aBoolean) {
                        PreferenceManager
                                .getDefaultSharedPreferences(context)
                                .edit()
                                .putBoolean("isFirst", false)
                                .apply();
                    }
                    return aBoolean;
                }
            })
            //返回:最新版本的信息
            .flatMap(new Function<Boolean, ObservableSource<String>>() {
                @Override
                public ObservableSource<String> apply(Boolean aBoolean) throws Exception {
                    Thread.sleep(300);
    
                    return new Observable<String>() {
                        @Override
                        protected void subscribeActual(Observer<? super String> observer) {
                            observer.onNext("update info");
                        }
                    };
                }
            })
            .observeOn(AndroidSchedulers.mainThread())
            //返回:是否版本更新
            .flatMap(new Function<String, ObservableSource<Boolean>>() {
                @Override
                public ObservableSource<Boolean> apply(String string) throws Exception {
                    if (string == null) {
                        return Observable.create(new ObservableOnSubscribe<Boolean>() {
                            @Override
                            public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
                                e.onNext(false);
                            }
                        });
                    } else {
                        return Observable.create(new ObservableOnSubscribe<Boolean>() {
                            @Override
                            public void subscribe(final ObservableEmitter<Boolean> e) throws Exception {
                                new AlertDialog.Builder(context)
                                        .setTitle("发现新版本")
                                        .setMessage("更新内容")
                                        .setPositiveButton("升级", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
    
                                            }
                                        })
                                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
    
                                            }
                                        })
                                        .setOnDismissListener(new DialogInterface.OnDismissListener() {
                                            @Override
                                            public void onDismiss(DialogInterface dialogInterface) {
                                                e.onNext(true);
                                            }
                                        })
                                        .create().show();
                            }
                        });
                    }
                }
            })
            .observeOn(Schedulers.io())
            //返回:弹窗工具信息
            .flatMap(new Function<Boolean, ObservableSource<String>>() {
    
                @Override
                public ObservableSource<String> apply(Boolean aBoolean) throws Exception {
                    Thread.sleep(300);
                    return Observable.create(new ObservableOnSubscribe<String>() {
                        @Override
                        public void subscribe(ObservableEmitter<String> e) throws Exception {
                            e.onNext("ok");
                        }
                    });
                }
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<String>() {
                @Override
                public void accept(String s) throws Exception {
                    Toast.makeText(HomeCheckActivity.this, s, Toast.LENGTH_SHORT).show();
                }
            });
    
    disposables.add(disposable);
    

    小结

    在熟悉了RxJava的基本概念之后,写Rx代码确实比较顺手,有一种行云流水的感觉。值得注意的是,使用RxJava进行开发并不会减少原有代码量,反而有一定的增加。遇到的主要问题就是,要理解并区分subscribeOn和observeOn的线程控制,以及map和flatMap的变换。

    我的粗浅理解是:

    observeOn作用于该操作符之后操作符直到出现新的observeOn操作符。subscribeOn作用于该操作符之前的 Observable 的创建操符作以及 doOnSubscribe 操作符。

    map是Observable对象没有改变,执行形式变了,比如有File变成Bitmap。而flatMap是Observable发生了改变,比如以前被观察的对象是sp里的isFirst,现在变成了引导界面的动画结束。

    源码地址:https://github.com/ihrthk/RxJava2SampleDemo/blob/master/app/src/main/java/me/zhangls/rxjava2sampledemo/HomeCheckActivity.java

    参考

    http://www.jianshu.com/p/59c3d6bb6a6b

    相关文章

      网友评论

          本文标题:小试牛刀RxJava2之首页检查

          本文链接:https://www.haomeiwen.com/subject/epwebttx.html