ReactiveX入门

为了表述方便 本文使用缩写Rx代替ReactiveX

目录

  • 第一行代码

    • 安装依赖

    • 第一段代码

    • 第二段代码

  • Rx是什么?

    • 多语言

    • 多平台

    • 微软开源

  • 三大对象(接口)

    • Observable

    • Observer

    • Subscription

  • 三大特性

    • Flow

    • Operators

    • Scheduler

  • 下一步

    • 响应式编程

    • FlatMap

第一行代码

安装依赖

cnpm i rxjs

cnpm i -g babel-cli

强烈要求使用nvm安装node环境 / 关于Babel的详细介绍参考Babel 入门教程

第一段代码

touch observable.js
var Rx = require('rxjs/Rx');

var observable = Rx.Observable.create(function (observer) {
    observer.next(1);
    setTimeout(() => {
        observer.next(2);
        observer.complete();
    }, 1000);
});
babel-node observable.js
// 没有任何打印信息

第二段代码

vim observable.js
console.log('just before subscribe');
observable.subscribe({
    next: x => console.log('got value ' + x),
    error: err => console.error('something wrong occurred: ' + err),
    complete: () => console.log('done'),
});
console.log('just after subscribe');
babel-node observable.js
just before subscribe
got value 1
just after subscribe
got value 2
done

互动问答: 从这段代码大家对Rx有哪些感受?

Rx是什么?

ReactiveX is a library for composing asynchronous and event-based programs by using observable sequences

多语言

RxJava / RxJS / Rx.NET / RxScala / RxClojure / RxSwift etc.

多平台

RxNetty / RxAndroid / RxCocoa

微软开源

Rx / VS Code / TypeScript etc.

更多微软开源参考Github Microsoft

三大对象(接口)

Observable

原型定义
create(onSubscription: function(observer: Observer): TeardownLogic) Observable
创建一个新的Observable 当观察者(Observer)订阅该(Observable)时 它会执行指定的函数

touch objects.js
var Rx = require('rxjs/Rx');

var observable = Rx.Observable.create(function subscribe(observer) {
    var id = setInterval(() => {
        observer.next('hi')
    }, 1000);
});
babel-node objects.js

Observer

原型定义:
interface Observer {
closed?: boolean;
next: (value: T) => void;
error: (err: any) => void;
complete: () => void;
}

vim objects.js
observable.subscribe({
    next: x => console.log('got value ' + x),
    error: err => console.error('something wrong occurred: ' + err),
    complete: () => console.log('done'),
});
babel-node objects.js

Subscription

原型定义
subscribe(observerOrNext: Observer | Function, error: Function, complete: Function): ISubscription
调用Observable的执行并注册Observer的处理器以便于发出通知

vim objects.js
var subscription = observable.subscribe(x => console.log(x.toUpperCase()));
setInterval(() => {
    subscription.unsubscribe();
}, 1000);
babel-node objects.js

三大特性

Flow

touch characters.html




    
    rxjs-demo
    



    
    



vim characters.html

    
    

ReactiveX入门_第1张图片
rx-flow.gif

纯函数的好处

Operators

  • scan
vim characters.html

    
    

ReactiveX入门_第2张图片
rx-scan.png
  • throttle
vim characters.html

    
    

ReactiveX入门_第3张图片
rx-throttle.png
  • map
vim characters.html

    
    

ReactiveX入门_第4张图片
rx-map.png

Scheduler

private void login(String phone, String password) {
    Type type = new TypeToken>() {
    }.getType();
    HttpRequest apiRequest = new HttpRequest.Builder()
        .setUrl(ApiEndPoint.ENDPOINT_LOGIN)
        .setParam("phone", phone)
        .setParam("password", password)
        .setParam("auto_login", "1")
        .build();
    getDataManager().>post(type, apiRequest)
        .subscribeOn(Schedulers.io())
        .doOnSubscribe(new Consumer() {
            @Override
            public void accept(@NonNull Disposable disposable) throws Exception {
                LoggerUtil.i("showLoading");
            }
        })
        .map(new Function, User>() {
            @Override
            public User apply(@NonNull HttpResponse response) throws Exception {
                return response.getData();
            }
        })
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer() {
            @Override
            public void onSubscribe(@NonNull Disposable disposable) {
                addDisposable(disposable);
            }

            @Override
            public void onNext(@NonNull User user) {
                LoggerUtil.i(user.toString());
                getDataManager().setAccessToken(user.getId().toString());
            }

            @Override
            public void onError(@NonNull Throwable e) {
                LoggerUtil.i("dismissLoading");
                LoggerUtil.i("onError");
            }

            @Override
            public void onComplete() {
                LoggerUtil.i("dismissLoading");
                getNavigator().goToMainActivity();
            }
        });
}

详细参考android-mvvm-boilerplate

下一步

响应式编程

  • Vue.js / React / AngularJS

  • Data Binding Library

FlatMap

  • FlatMap

参考

  • Babel 入门教程

  • RxJS

  • Understanding RxJava Subject — Publish, Replay, Behavior and Async Subject

  • RxSwift 函数响应式编程

  • 用 RxSwift + Moya 写出优雅的网络请求代码

你可能感兴趣的:(ReactiveX入门)