Promise
主要功能,解决了回调地狱的问题
类比Promise和RxJS
//以下是promise的写法
let promise = new Promise(resolve => {
setTimeout(() => {
resolve('-----promise timeout------')
},2000)
})
promsie.then(value => console.log(value))
//以下是Observable写法
let stream1$ = new Observable(observable => {
let timeout = setTimeout(() => {
observable.next('observable timeout')
},2000);
return () => {
clearTimeout(timeout);
}
});
let disposable = stream1$.subscribe(value => console.log(value))
//第一个核心不同点:Observable是可以中途取消的,而Promise不可以
setTimeout(() => {
disposable.unsubscribe();
},1000);
//第二个核心不同点:Observable可以持续发射很多值,而Promise只能兑现一次
let stream2$ = new Observable<number>(observer => {
let count = 0;
let interval = setInterval(() => {
observer.next(count++);
},1000);
return () => {
clearInterval(interval);
};
});
stream2$.subscribe(value => console.log('Observable>'+value));
//第三个核心不同点:Observable提供了很多工具函数
stream2$
.filter(val=>val%2==0)
.subscribe(value => console.log('filter>)'+value);
stream2$
.map(value => value * value)
.subscribe(value => console.log('map>'+value));
debounceTime
public searchTextStream:Subject<string> = new Subject<string>();
this.searchTextStream
.debounceTime(500) //500ms没有按键,发送请求
.distinctUntilChanged() //有按键,内容没有变化,类似于Ctrl键等不发送请求
.subscribe(searchText => {
console.log(this.searchText);
this.loadData(this.searchText);
});