Android 架构师之路22 响应式编程RxJava 整体变换

Android 架构师之路 目录

前言

整体变换简介
  1. 将一坨变换整合起来放在一起
  2. 用于固定的变换场景

整体变换体现了响应式编程思想:通过Transformer实现整体变化,变化后能向下传播。

1.RxJava1 整体变换实例
                Observable.create(new Observable.OnSubscribe<String>() {
                    @Override
                    public void call(Subscriber<? super String> subscriber) {
                        if (!subscriber.isUnsubscribed()) {
                            subscriber.onNext("test");
                            Log.d(TAG, "currentThread:" + Thread.currentThread());
                            subscriber.onCompleted();
                        }
                    }
                }).compose(new Observable.Transformer<String, String>() {

                    @Override
                    public Observable<String> call(Observable<String> stringObservable) {
                        return stringObservable.
                                subscribeOn(Schedulers.newThread()).
                                observeOn(AndroidSchedulers.mainThread());
                    }
                }).subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(String s) {
                        Log.d(TAG, "onNext:" + s);
                        Log.d(TAG, "currentThread:" + Thread.currentThread());
                    }
                });

06-19 14:26:18.275 12255-12350/com.haocai.rxjavademo D/kpioneer: currentThread:Thread[RxNewThreadScheduler-1,5,main]
06-19 14:26:18.275 12255-12255/com.haocai.rxjavademo D/kpioneer: onNext:test
06-19 14:26:18.275 12255-12255/com.haocai.rxjavademo D/kpioneer: currentThread:Thread[main,5,main]
2.RxJava2 整体变换实例
                   /*---------无背压---------*/
                Observable.
                        create(new ObservableOnSubscribe<String>() {
                            @Override
                            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                                if (!emitter.isDisposed()) {
                                    Log.d(TAG, "无背压 currentThread:" + Thread.currentThread());
                                    emitter.onNext("test");
                                    emitter.onComplete();
                                }
                            }
                        }).
                        compose(new ObservableTransformer<String, String>() {
                            @Override
                            public ObservableSource<String> apply(Observable<String> upstream) {
                                return upstream.
                                        subscribeOn(Schedulers.newThread()).
                                        observeOn(AndroidSchedulers.mainThread());
                            }
                        }).
                        subscribe(new Observer<String>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(String o) {
                                Log.d(TAG, "无背压 onNext:" + o);
                                Log.d(TAG, "无背压 currentThread:" + Thread.currentThread());

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });

                  /*---------有背压---------*/
                Flowable.
                        create(new FlowableOnSubscribe<String>() {
                            @Override
                            public void subscribe(FlowableEmitter<String> emitter) throws Exception {
                                if (!emitter.isCancelled()) {
                                    Log.d(TAG, "有背压 currentThread:" + Thread.currentThread());
                                    emitter.onNext("test");
                                    emitter.onComplete();
                                }
                            }
                        }, BackpressureStrategy.DROP).
                        compose(new FlowableTransformer<String, String>() {
                            @Override
                            public Publisher<String> apply(Flowable<String> upstream) {
                                return upstream.
                                        subscribeOn(Schedulers.newThread()).
                                        observeOn(AndroidSchedulers.mainThread());
                            }
                        }).
                        subscribe(new Subscriber<String>() {
                            @Override
                            public void onSubscribe(Subscription s) {
                                s.request(Long.MAX_VALUE);
                            }

                            @Override
                            public void onNext(String s) {
                                Log.d(TAG, "有背压 onNext:" + s);
                                Log.d(TAG, "有背压 currentThread:" + Thread.currentThread());
                            }

                            @Override
                            public void onError(Throwable t) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });

06-19 14:45:08.515 17301-17407/com.haocai.rxjavademo D/kpioneer: 无背压 currentThread:Thread[RxNewThreadScheduler-1,5,main]
06-19 14:45:08.515 17301-17301/com.haocai.rxjavademo D/kpioneer: 无背压 onNext:test
06-19 14:45:08.515 17301-17301/com.haocai.rxjavademo D/kpioneer: 无背压 currentThread:Thread[main,5,main]
06-19 14:45:08.525 17301-17408/com.haocai.rxjavademo D/kpioneer: 有背压 currentThread:Thread[RxNewThreadScheduler-2,5,main]
06-19 14:45:08.535 17301-17301/com.haocai.rxjavademo D/kpioneer: 有背压 onNext:test
06-19 14:45:08.535 17301-17301/com.haocai.rxjavademo D/kpioneer: 有背压 currentThread:Thread[main,5,main]

3.RxJava1 Transformer原理分析

  1. 继承自Func1接口,泛型参数是两个Observable
    public interface Transformer<T, R> extends Func1<Observable<T>, Observable<R>> {
        // cover for generics insanity
    }
  1. 为compose方法的入参
    public <R> Observable<R> compose(Transformer<? super T, ? extends R> transformer) {
        return ((Transformer<T, R>) transformer).call(this);
    }
  1. 传入一个Observable返回一个Observable

4.RxJava2 Transformer原理分析

4.1.RxJava2(无背压) ObservableTransformer
  1. 有一个apply方法
  2. 传入一个Observable返回一个新的Observable
  3. 为compose方法的入参

/**
 * Interface to compose Observables.
 *
 * @param <Upstream> the upstream value type
 * @param <Downstream> the downstream value type
 */
public interface ObservableTransformer<Upstream, Downstream> {
    /**
     * Applies a function to the upstream Observable and returns an ObservableSource with
     * optionally different element type.
     * @param upstream the upstream Observable instance
     * @return the transformed ObservableSource instance
     */
    @NonNull
    ObservableSource<Downstream> apply(@NonNull Observable<Upstream> upstream);
}

    /**
     * Wraps an ObservableSource into an Observable if not already an Observable.
     *
     * <dl>
     *  <dt><b>Scheduler:</b></dt>
     *  <dd>{@code wrap} does not operate by default on a particular {@link Scheduler}.</dd>
     * </dl>
     *
     * @param <T> the value type
     * @param source the source ObservableSource instance
     * @return the new Observable instance or the same as the source
     * @throws NullPointerException if source is null
     */
    @CheckReturnValue
    @SchedulerSupport(SchedulerSupport.NONE)
    public static <T> Observable<T> wrap(ObservableSource<T> source) {
        ObjectHelper.requireNonNull(source, "source is null");
        if (source instanceof Observable) {
            return RxJavaPlugins.onAssembly((Observable<T>)source);
        }
        return RxJavaPlugins.onAssembly(new ObservableFromUnsafeSource<T>(source));
    }
    public final <R> Observable<R> compose(ObservableTransformer<? super T, ? extends R> composer) {
        return wrap(((ObservableTransformer<T, R>) ObjectHelper.requireNonNull(composer, "composer is null")).apply(this));
    }
4.2.RxJava2(有背压) FlowableTransformer
  1. 有一个apply方法
  2. 传入一个Flowable返回一个新的Flowable
  3. 为compose方法的入参
public interface FlowableTransformer<Upstream, Downstream> {
    /**
     * Applies a function to the upstream Flowable and returns a Publisher with
     * optionally different element type.
     * @param upstream the upstream Flowable instance
     * @return the transformed Publisher instance
     */
    @NonNull
    Publisher<Downstream> apply(@NonNull Flowable<Upstream> upstream);
}
    @CheckReturnValue
    @BackpressureSupport(BackpressureKind.PASS_THROUGH)
    @SchedulerSupport(SchedulerSupport.NONE)
    @SuppressWarnings("unchecked")
    public static <T> Flowable<T> fromPublisher(final Publisher<? extends T> source) {
        if (source instanceof Flowable) {
            return RxJavaPlugins.onAssembly((Flowable<T>)source);
        }
        ObjectHelper.requireNonNull(source, "publisher is null");

        return RxJavaPlugins.onAssembly(new FlowableFromPublisher<T>(source));
    }
    @SuppressWarnings("unchecked")
    @CheckReturnValue
    @BackpressureSupport(BackpressureKind.PASS_THROUGH)
    @SchedulerSupport(SchedulerSupport.NONE)
    public final <R> Flowable<R> compose(FlowableTransformer<? super T, ? extends R> composer) {
        return fromPublisher(((FlowableTransformer<T, R>) ObjectHelper.requireNonNull(composer, "composer is null")).apply(this));
    }

5.RxJava1 Transformer仿写

    public interface Converter<T, R> extends Func1<Caller<T>, Caller<R>> {

    }

    public final <R> Caller<R> unify(Converter<T, R> converter) {
        return converter.call(this);
    }
实例
public class Lesson4_2Activity extends AppCompatActivity {
    public static final String TAG = "kpioneer";

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_test);
        ButterKnife.bind(this);

    }

    @OnClick(R.id.testDo)
    public void onViewClicked() {
        Caller.
                create(new Caller.OnCall<String>() {
                    @Override
                    public void call(Receiver<String> stringReceiver) {
                        stringReceiver.onReceive("test");
                        Log.d(TAG, "currentThread:" + Thread.currentThread());
                    }
                }).
                unify(new Caller.Converter<String, String>() {
                    @Override
                    public Caller<String> call(Caller<String> stringCaller) {
                        return stringCaller.
                                callOn(new NewThreadSwitcher()).
                                callbackOn(new LooperSwitcher(getMainLooper()));
                    }
                }).
                call(new Receiver<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable t) {

                    }

                    @Override
                    public void onReceive(String s) {
                        Log.d(TAG, "onNext:" + s);
                        Log.d(TAG, "currentThread:" + Thread.currentThread());
                    }
                });
    }
}
06-19 15:55:38.735 477-477/com.haocai.rxjavademo D/kpioneer: onNext:test
06-19 15:55:38.735 477-477/com.haocai.rxjavademo D/kpioneer: currentThread:Thread[main,5,main]
06-19 15:55:38.735 477-1180/com.haocai.rxjavademo D/kpioneer: currentThread:Thread[ NewThreadWorker,5,main]

6.RxJava2 Transformer仿写

6.1RxJava2 无背压
    public <R> Caller<R> unify(CallerConverter<T,R> callerConverter){
        return callerConverter.convert(this);
    }
/**
 * Created by Xionghu on 2018/6/19.
 * Desc: 用于整体变换
 */

public interface TelephonerConverter<T,R> {
    Telephoner<R> convert(Telephoner<T> telephoner);
}
6.2RxJava2 有背压
    public <R> Telephoner<R> unify(TelephonerConverter<T, R> tTelephonerConverter) {
        return tTelephonerConverter.convert(this);
    }
/**
 * Created by Xionghu on 2018/6/19.
 * Desc: 用于整体变换
 */

public interface TelephonerConverter<T,R> {
    Telephoner<R> convert(Telephoner<T> telephoner);
}
6.3实例
/**
 * Created by Xionghu on 2018/6/11.
 * Desc: RxJava2  整体变换仿写
 */

public class Lesson4_3Activity extends AppCompatActivity {
    public static final String TAG = "kpioneer";

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_test);
        ButterKnife.bind(this);

    }

    @OnClick(R.id.testDo)
    public void onViewClicked() {
        Caller.
                create(new CallerOnCall<String>() {
                    @Override
                    public void call(CallerEmitter<String> callerEmitter) {
                        callerEmitter.onReceive("test");
                        Log.d(TAG, "无背压 currentThread:" + Thread.currentThread());
                    }
                }).
                unify(new CallerConverter<String, String>() {
                    @Override
                    public Caller<String> convert(Caller<String> caller) {
                        return caller.
                                callOn(new NewThreadSwitcher()).
                                callbackOn(new LooperSwitcher(getMainLooper()));
                    }
                }).
                call(new Callee<String>() {
                    @Override
                    public void onCall(Release release) {

                    }

                    @Override
                    public void onReceive(String s) {
                        Log.d(TAG, "无背压 onReceive:" + s);
                        Log.d(TAG, "无背压 currentThread:" + Thread.currentThread());
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable t) {

                    }
                });

        Telephoner.
                create(new TelephonerOnCall<String>() {
                    @Override
                    public void call(TelephonerEmitter<String> telephonerEmitter) {
                        telephonerEmitter.onReceive("test");
                        Log.d(TAG, "有背压 currentThread:" + Thread.currentThread());
                    }
                }).
                unify(new TelephonerConverter<String, String>() {
                    @Override
                    public Telephoner<String> convert(Telephoner<String> telephoner) {
                        return telephoner.
                                callOn(new NewThreadSwitcher()).
                                callbackOn(new LooperSwitcher(getMainLooper()));
                    }
                }).
                call(new Receiver<String>() {
                    @Override
                    public void onCall(Drop d) {
                        d.request(Long.MAX_VALUE);
                    }

                    @Override
                    public void onReceive(String s) {
                        Log.d(TAG, "有背压 onReceive:" + s);
                        Log.d(TAG, "有背压 currentThread:" + Thread.currentThread());
                    }

                    @Override
                    public void onError(Throwable t) {

                    }

                    @Override
                    public void onCompleted() {

                    }
                });

    }
}
06-19 16:28:23.215 11452-11698/com.haocai.rxjavademo D/kpioneer: 无背压 currentThread:Thread[NewThreadWorker,5,main]
06-19 16:28:23.235 11452-11703/com.haocai.rxjavademo D/kpioneer: 有背压 currentThread:Thread[NewThreadWorker,5,main]
06-19 16:28:23.235 11452-11452/com.haocai.rxjavademo D/kpioneer: 无背压 onReceive:test
06-19 16:28:23.235 11452-11452/com.haocai.rxjavademo D/kpioneer: 无背压 currentThread:Thread[main,5,main]
06-19 16:28:23.235 11452-11452/com.haocai.rxjavademo D/kpioneer: 有背压 onReceive:test
06-19 16:28:23.235 11452-11452/com.haocai.rxjavademo D/kpioneer: 有背压 currentThread:Thread[main,5,main]

源码下载

https://github.com/kpioneer123/RxJavaLearning

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

推荐阅读更多精彩内容