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

Android 架构师之路 目录

前言

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

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

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

                    @Override
                    public Observable call(Observable stringObservable) {
                        return stringObservable.
                                subscribeOn(Schedulers.newThread()).
                                observeOn(AndroidSchedulers.mainThread());
                    }
                }).subscribe(new Observer() {
                    @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() {
                            @Override
                            public void subscribe(ObservableEmitter emitter) throws Exception {
                                if (!emitter.isDisposed()) {
                                    Log.d(TAG, "无背压 currentThread:" + Thread.currentThread());
                                    emitter.onNext("test");
                                    emitter.onComplete();
                                }
                            }
                        }).
                        compose(new ObservableTransformer() {
                            @Override
                            public ObservableSource apply(Observable upstream) {
                                return upstream.
                                        subscribeOn(Schedulers.newThread()).
                                        observeOn(AndroidSchedulers.mainThread());
                            }
                        }).
                        subscribe(new Observer() {
                            @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() {
                            @Override
                            public void subscribe(FlowableEmitter emitter) throws Exception {
                                if (!emitter.isCancelled()) {
                                    Log.d(TAG, "有背压 currentThread:" + Thread.currentThread());
                                    emitter.onNext("test");
                                    emitter.onComplete();
                                }
                            }
                        }, BackpressureStrategy.DROP).
                        compose(new FlowableTransformer() {
                            @Override
                            public Publisher apply(Flowable upstream) {
                                return upstream.
                                        subscribeOn(Schedulers.newThread()).
                                        observeOn(AndroidSchedulers.mainThread());
                            }
                        }).
                        subscribe(new Subscriber() {
                            @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 extends Func1, Observable> {
        // cover for generics insanity
    }
  1. 为compose方法的入参
    public  Observable compose(Transformer transformer) {
        return ((Transformer) 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  the upstream value type
 * @param  the downstream value type
 */
public interface ObservableTransformer {
    /**
     * 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 apply(@NonNull Observable upstream);
}

    /**
     * Wraps an ObservableSource into an Observable if not already an Observable.
     *
     * 
*
Scheduler:
*
{@code wrap} does not operate by default on a particular {@link Scheduler}.
*
* * @param 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 Observable wrap(ObservableSource source) { ObjectHelper.requireNonNull(source, "source is null"); if (source instanceof Observable) { return RxJavaPlugins.onAssembly((Observable)source); } return RxJavaPlugins.onAssembly(new ObservableFromUnsafeSource(source)); }
    public final  Observable compose(ObservableTransformer composer) {
        return wrap(((ObservableTransformer) ObjectHelper.requireNonNull(composer, "composer is null")).apply(this));
    }
4.2.RxJava2(有背压) FlowableTransformer
  1. 有一个apply方法
  2. 传入一个Flowable返回一个新的Flowable
  3. 为compose方法的入参
public interface FlowableTransformer {
    /**
     * 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 apply(@NonNull Flowable upstream);
}
    @CheckReturnValue
    @BackpressureSupport(BackpressureKind.PASS_THROUGH)
    @SchedulerSupport(SchedulerSupport.NONE)
    @SuppressWarnings("unchecked")
    public static  Flowable fromPublisher(final Publisher source) {
        if (source instanceof Flowable) {
            return RxJavaPlugins.onAssembly((Flowable)source);
        }
        ObjectHelper.requireNonNull(source, "publisher is null");

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

5.RxJava1 Transformer仿写

    public interface Converter extends Func1, Caller> {

    }

    public final  Caller unify(Converter 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() {
                    @Override
                    public void call(Receiver stringReceiver) {
                        stringReceiver.onReceive("test");
                        Log.d(TAG, "currentThread:" + Thread.currentThread());
                    }
                }).
                unify(new Caller.Converter() {
                    @Override
                    public Caller call(Caller stringCaller) {
                        return stringCaller.
                                callOn(new NewThreadSwitcher()).
                                callbackOn(new LooperSwitcher(getMainLooper()));
                    }
                }).
                call(new Receiver() {
                    @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  Caller unify(CallerConverter callerConverter){
        return callerConverter.convert(this);
    }
/**
 * Created by Xionghu on 2018/6/19.
 * Desc: 用于整体变换
 */

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

public interface TelephonerConverter {
    Telephoner convert(Telephoner 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() {
                    @Override
                    public void call(CallerEmitter callerEmitter) {
                        callerEmitter.onReceive("test");
                        Log.d(TAG, "无背压 currentThread:" + Thread.currentThread());
                    }
                }).
                unify(new CallerConverter() {
                    @Override
                    public Caller convert(Caller caller) {
                        return caller.
                                callOn(new NewThreadSwitcher()).
                                callbackOn(new LooperSwitcher(getMainLooper()));
                    }
                }).
                call(new Callee() {
                    @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() {
                    @Override
                    public void call(TelephonerEmitter telephonerEmitter) {
                        telephonerEmitter.onReceive("test");
                        Log.d(TAG, "有背压 currentThread:" + Thread.currentThread());
                    }
                }).
                unify(new TelephonerConverter() {
                    @Override
                    public Telephoner convert(Telephoner telephoner) {
                        return telephoner.
                                callOn(new NewThreadSwitcher()).
                                callbackOn(new LooperSwitcher(getMainLooper()));
                    }
                }).
                call(new Receiver() {
                    @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

你可能感兴趣的:(Android 架构师之路22 响应式编程RxJava 整体变换)