响应式编程
以下概念介绍,基于 node v10.16.3 版本进行。不满足条件的,请移步 google or 度娘。
概念介绍
const a = 1,b = 2;
const c = a+ b;
响应式编程,当a,b再次变化时,c会再次做出修改。
背景
- RxJS是一个用于使用Observables进行响应式编程的库
- 可简化编写异步或基于回调的代码
本地环境搭建
- node
- npm script
- rollup
npm install --global rollup
- rxjs
npm install rxjs
- es6 语法,利用tree-shaking ,缩减代码
使用
hello-world 之123
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
of(1,2,3).subscribe(res => {
console.log(res);
});
rollup打包→ bundle.js → node bundle.js,连续输出123
rollup main.js --file bundle.js --format cjs
'use strict';
var rxjs = require('rxjs');
require('rxjs/operators');
rxjs.of(1,2,3).subscribe(res => {
console.log(res);
});
优化rollup配置
创建rollup.config.js
export default {
input: 'main.js',
output: {
file: 'bundle.js',
format: 'cjs'
}
};
rollup -c rollup.config.js
npm script支持
package.json
{
"name": "rxjs-demo",
"version": "1.0.0",
"description": "",
"main": "test.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build":"rollup -c", // 默认配置 rollup --config rollup.config.js
"start":"npm run build && node bundle.js" // && 是继发,& 是并发
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"rxjs": "^6.5.3"
}
}
最终的运行如下:
npm start
Rxjs读取package.json字段version
// install plugin
npm install --save-dev rollup-plugin-json
// rollup.config.js
import json from 'rollup-plugin-json';
export default {
input: 'main.js',
output: {
file: 'bundle.js',
format: 'cjs'
},
plugins:[json()]
};
// main.js
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
import { version } from './package.json';
of(1,2,3,version).subscribe(res => {
console.log(res);
});
pipe管道在输出前修改数据
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
import { version } from './package.json';
of(1,2,3,version).pipe(map(item => item + ' through pipe use map'))
.subscribe(res => {
console.log(res);
});
用Observable改写of
其中,可以看到observable属于异步执行。
import { of,Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { version } from './package.json';
//through pipe
// of(1,2,3,version).pipe(map(item => item + ' through pipe use map'))
// .subscribe(res => {
// console.log(res);
// });
console.log("before observable....");
const publisher$ = new Observable(suber => {
console.log("in observable....");
suber.next(1);
suber.next(2);
suber.next(3);
suber.next(version);
});
console.log("after observable....");
publisher$.pipe(map(item => item + ' through pipe use map')).subscribe(res => {
console.log(res);
});
subscribe订阅几次,通知执行几次,而不是仅消费一次
console.log("before observable....");
const publisher$ = new Observable(suber => {
console.log("in observable....");
suber.next(1);
suber.next(2);
suber.next(3);
suber.next(version);
});
console.log("after observable....");
publisher$.pipe(map(item => item + ' through pipe use map')).subscribe(res => {
console.log(res);
});
publisher$.subscribe(res => {
console.log("subscribe second..." + res);
});
hot subscribe - 与时间先后有关,订阅内容差
import { of,Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { version } from './package.json';
let count = 0;
console.log("before observable....");
const publisher$ = new Observable(suber => {
console.log("in observable....");
setInterval(() => {
count++;
suber.next(count);
}, 100);
});
console.log("after observable....");
publisher$.pipe(map(item => 'first ...'+ item)).subscribe(res => {
console.log(res);
});
setTimeout(() => {
const publisher2$ = new Observable(suber => {
setInterval(() => {
suber.next(count);
}, 100);
});
publisher2$.subscribe(res => {
console.log("second ..." + res);
});
}, 1000);
cold subscribe – 时间先后无关,内容无差异
import { of,Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { version } from './package.json';
console.log("before observable....");
const publisher$ = new Observable(suber => {
console.log("in observable....");
setInterval(() => {
let count = 0;
count++;
suber.next(count);
}, 100);
});
console.log("after observable....");
publisher$.pipe(map(item => 'first ...'+ item)).subscribe(res => {
console.log(res);
});
setTimeout(() => {
const publisher2$ = new Observable(suber => {
setInterval(() => {
let count = 0;
count++;
suber.next(count);
}, 100);
});
publisher2$.subscribe(res => {
console.log("second ..." + res);
});
}, 1000);
observable状态终止
import { of,Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { version } from './package.json';
const publiser$ = new Observable(suber => {
suber.next(1);
suber.next(2);
suber.next(3);
suber.next(version);
// suber.complete();
suber.error();
});
publiser$.subscribe({
next:res => {
console.log(`next ...${res}`);
},
complete:() => {
console.log("complete done....");
},
error: () => {
console.log("error occur....");
}
});
停止订阅,释放资源,但状态没有终止
import { of,Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { version } from './package.json';
const publiser$ = new Observable(suber => {
let count = 0;
const timer = setInterval(() => {
suber.next(count);
count++;
},400);
//suber.next(1);
// suber.complete();
// suber.error();
return {
unsubscribe:() => {
console.log("stop push data....");
clearInterval(timer);
}
}
});
const unsuber = publiser$.subscribe({
next:res => {
console.log(`next ...${res}`);
},
complete:() => {
console.log("complete done....");
},
error: () => {
console.log("error occur....");
}
});
setTimeout(() => {
unsuber.unsubscribe();
},2000);
利用rxjs自带操作符优化上述的取消订阅
import { of,Observable, interval } from 'rxjs';
import { map } from 'rxjs/operators';
import { version } from './package.json';
const publiser$ = interval(400);
const unsuber = publiser$.subscribe({
next:res => {
console.log(`next ...${res}`);
},
complete:() => {
console.log("complete done....");
},
error: () => {
console.log("error occur....");
}
});
setTimeout(() => {
unsuber.unsubscribe();
},2000);
双重身份的SubJect
import { of,Observable, interval,Subject } from 'rxjs';
import { map } from 'rxjs/operators';
import { version } from './package.json';
const sub = new Subject();
sub.pipe(map(res => 'first ...'+res)).subscribe((res) => {
console.log("sub one...",res);
});
sub.subscribe({
next:(res) => {
console.log(`second...${res}`);
}
});
sub.next(1);
sub.next(2);
import { of,Observable, interval,Subject ,from} from 'rxjs';
import { map } from 'rxjs/operators';
import { version } from './package.json';
const sub = new Subject();
sub.pipe(map(res => 'first ...'+res)).subscribe((res) => {
console.log("sub one...",res);
});
sub.subscribe({
next:(res) => {
console.log(`second...${res}`);
}
});
// sub.next(1);
// sub.next(2);
const publisher$ = from([1,2,3]);
publisher$.subscribe(sub);
参考文献
本文作者:前端首席体验师(CheongHu)
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦