Rxjs 项目实战例子大全

此文会将平时在项目中所遇到的例子整合起来一起演示,使用的是 rxviz.com上的弹珠图。

依赖

{
  "name": "rxjs",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "react": "^16.3.2",
    "rxjs": "^6.1.0",
    "rxjs-compat": "^6.1.0"
  }
}

请求依赖并发

描述:发起一个用户登录请求,成功后再发送3个查询请求(资料,邮件,消息),最后将结果合并输出结果。

const {Observable} = require('rxjs/Rx');
const loginRequest = new Promise((resolve, reject) => {
    setTimeout(function () {
        resolve({sessionId:'xxx-xxx-xxx'})
    }, 2000);
});
const queryInfoRequest = function (sessionId) {
    return new Promise((resolve, reject) => {
            setTimeout(function () {
                resolve({
                    id:1,
                    nickName:'lake'
                })
            }, 1000)
        }
    )
};
const queryEmailRequest = function (sessionId) {
    return new Promise((resolve, reject) => {
            setTimeout(function () {
                resolve([
                    {id:1,title:'hi',content:'I miss you'},
                    {id:2,title:'are you there',content:'how are you doing'}
                    ])
            }, 1000)
        }
    )
};
const queryMessageRequest = function (sessionId) {
    return new Promise((resolve, reject) => {
            setTimeout(function () {
                resolve([
                    {id:1,type:'TEXT',content:'I am ok'},
                    {id:2,type:'TEXT',content:'yeah'}
                ])
            }, 1000)
        }
    )
};
const oldTime = new Date().getTime();
Observable.fromPromise(loginRequest)
    .flatMap(sessionId=>{
        return [
            Observable.fromPromise(queryInfoRequest(sessionId)),
            Observable.fromPromise(queryEmailRequest(sessionId)),
            Observable.fromPromise(queryMessageRequest(sessionId)),
        ];
    })
    .combineAll()
    .subscribe(value => {
        console.log(value);
        console.log("总运行时长:"+(new Date() - oldTime));
    });

运行结果

[nodemon] starting `node index.js`
[ { id: 1, nickName: 'lake' },
  [ { id: 1, title: 'hi', content: 'I miss you' },
    { id: 2, title: 'are you there', content: 'how are you doing' } ],
  [ { id: 1, type: 'TEXT', content: 'I am ok' },
    { id: 2, type: 'TEXT', content: 'yeah' } ] ]
总运行时长:3017

你可能感兴趣的:(Rxjs 项目实战例子大全)