我正在尝试在HTTP请求上实施背压策略,以在某些条件下暂时阻止待处理请求数秒。暂停的逻辑将基于另一个Observable。
我的研究和理解使我相信pausableBuffered
运算符完全符合我的需要。在此记录http://reactivex.io/documentation/operators/backpressure.html。
但是我在ReactiveX v5(5.0.0-beta.0)中找不到此运算符,并且迁移指南(v4-v5)似乎表明它们已被删除。如果是这种情况,如何使用v5可用运算符实现所需的结果?
答案 0 :(得分:3)
背压故事现在完全是dropped。
这是获得相同结果的一种方法:
const pausableBuffered = (observable, pauser) => {
const subj = new rx.Subject();
let buffer = [];
const nextEmitter = x => subj.next(x);
const nextBuffer = x => buffer.push(x);
let subscriber = nextEmitter;
observable.subscribe(x => subscriber(x));
pauser.subscribe(value => {
if (value) {
subscriber = nextBuffer;
} else {
buffer.forEach(nextEmitter);
buffer = [];
subscriber = nextEmitter;
}
})
return subj;
};
答案 1 :(得分:0)
我偶然发现了这个答案,对于我的用例,我把它变成了一个管道
import { Observable, Subject, Subscription } from "rxjs";
export function pausable(pauseToken: Observable<boolean>, startPuased: boolean, lastOnly: boolean) {
return function <T>(source: Subject<T>): Observable<T> {
let buffer: T[] = [];
const nextEmitter = (x: T) => subj.next(x);
const nextBuffer = (x: any) => buffer.push(x);
var sourceSubscription: Subscription;
var pauseSubscription: Subscription;
var subj = new Subject<T>();
let subscriber = nextEmitter;
if (startPuased) {
subscriber = nextBuffer;
}
sourceSubscription = source.subscribe({
next(value) {
subscriber(value);
},
error(error) {
subj.error(error);
},
complete() {
subj.complete();
pauseSubscription?.unsubscribe();
}
})
pauseSubscription = pauseToken.subscribe({
next(value) {
if (value) {
subscriber = nextBuffer;
} else {
if (lastOnly && buffer.length > 0) {
nextEmitter(buffer.pop())
} else {
buffer.forEach(nextEmitter);
}
buffer = [];
subscriber = nextEmitter;
}
},
complete() {
sourceSubscription?.unsubscribe();
pauseSubscription?.unsubscribe();
}
});
return subj;
}
}