我想构建一个包装类,它在Observable的每个发出值之前和之后执行某些操作。
这是我想出的:
class Wrapper<T> {
wrapped$: Observable<T>;
_dataSubject = new Subject<T>();
data$ = this._dataSubject.pipe(
tap(_ => console.log("BEFORE"),
//
// map( ??? )
//
);
constructor(wrapped$: Observable<T>) {
this.wrapped$ = wrapped$.pipe(
tap(_ => console.log("AFTER")
);
}
}
let subject = new Subject<string>();
let wrapper = new Wrapper(subject);
wrapper.data$.subscribe(val => console.log(val));
subject.next("foo")
控制台输出应为:
BEFORE
foo
AFTER
我无法弄清楚如何将$wrapped
Observable与_dataSubject
联系起来。
但也许我完全错了,需要采用不同的方法。
答案 0 :(得分:8)
这样的事情
import {Observable} from 'rxjs';
export class DoBeforeAfter<T> {
wrapped$: Observable<T>;
constructor(wrapped$: Observable<T>, doFunction: (data: any) => void) {
this.wrapped$ = Observable.of(null)
.do(_ => console.log("BEFORE"))
.switchMap(_ => wrapped$)
.do(doFunction)
.do(_ => console.log('AFTER'));
}
}
像这样消费
const source = Observable.of('NOW');
const beforeAfter = new DoBeforeAfter(source, data => console.log(data));
beforeAfter.wrapped$.subscribe(
null,
error => console.error(error),
() => console.log('DONE')
)
看起来有点麻烦,但也许它可以帮助
答案 1 :(得分:2)
最好的方法(尽管很复杂)是创建一个新的运算符,类似于tap
但是在发出值之前和之后都做了一些事情。
你可以看到它在示例中工作(它在ES6中,因为SO代码片段不接受TypeScript,但你会明白这一点)
function wrap(before, after) {
return function wrapOperatorFunction(source) {
return source.lift(new WrapOperator(before, after));
};
}
class WrapOperator {
constructor(before, after) {
this.before = before;
this.after = after;
}
call(subscriber, source) {
return source.subscribe(new WrapSubscriber(subscriber, this.before, this.after));
}
}
class WrapSubscriber extends Rx.Subscriber {
constructor(destination, before, after) {
super(destination);
this.before = before;
this.after = after;
}
_next(value) {
this.before ? this.before(value) : null;
this.destination.next(value);
this.after ? this.after(value) : null;
}
}
// Now:
const observable = Rx.Observable.from([1, 2, 3, 4]);
observable.pipe(
wrap(value => console.log('before', value), value => console.log('after', value))
).subscribe(value => console.log('value emitted', value), null, () => console.log('complete'));
// For what you want:
// let's simulate that, for each value in the array, we'll fetch something from an external service:
// we want the before to be executed when we make the request, and the after to be executed when it finishes. In this // case, we just combine two wrap operators and flatMap, for example:
observable.pipe(
wrap(value => console.log('BEFORE REQUEST', value)),
Rx.operators.flatMap(value => {
const subject = new Rx.Subject();
setTimeout(() => { subject.next(value); subject.complete(); }, 5000);
return subject;
}),
wrap(undefined, value => console.log('AFTER REQUEST', value))
).subscribe(value => console.log('value emitted', value), null, () => console.log('complete'));
<script src="https://unpkg.com/@reactivex/rxjs@5.5.0/dist/global/Rx.js"></script>
如上所述,可能有点复杂,但它与RxJS运算符无缝集成,它总是一个很好的例子,知道如何创建自己的运算符: - )
对于您在评论中所说的内容,您可以查看最后一个示例。在那里,我组合了两个wrap
运算符。第一个只使用before
回调,因此它只在发出值之前执行某些操作。如您所见,因为源可观察源来自数组,所以会立即执行四个before
回调。然后,我们应用flatMap
。对此,我们应用了新的wrap
,但这次仅使用after
回调。因此,只有在flatMap
返回的observable产生它们的值后才会调用此回调。
当然,如果是数组中的一个observable,你可以使用一个事件监听器,你可以:
before
回调是在observable推送事件触发之前执行的。after
回调。这是让运营商得到回报的地方,因为它们很容易合并。希望这适合你。
答案 2 :(得分:2)
所以,根据我的理解,你可以这样做:
var myFilter = new HttpBaseProtocolFilter();
myFilter.AllowUI = false;
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(myFilter);
Windows.Web.Http.HttpResponseMessage result = await client.GetAsync(new Uri("http://localhost:5132/api/values"));
然后:
class Wrapper<T> {
_dataSubject: Subject<T>;
wrapped$: Observable<T>;
constructor(wrapped$: Subject<T>) {
this._dataSubject = wrapped$;
this.wrapped$ = this._dataSubject.pipe(
tap(_ => console.log("BEFORE")),
tap(data => console.log(data)),
tap(_ => console.log("AFTER"))
);
}
}
答案 3 :(得分:0)
感谢您的所有投入!
我现在想出了自己的解决方案。 AFTER
和DATA
输出的顺序错误,但我发现只要它们同时出现就不重要
代码仍然需要一些重构,但至少它现在可以工作了!
class Wrapper {
_taskDoneSubject = new Subject<boolean>();
taskDone$ = this._taskDoneSubject.asObservable();
wrappedSwitchMap<T, R>(wrapped: (val: T) => Observable<R>): OperatorFunction<T, R> {
return switchMap<T, R>(val => { // can also be done using mergeMap
this._taskDoneSubject.next(false);
return wrapped(val).pipe(
tap(_ => this._taskDoneSubject.next(true))
);
});
}
}
用法:
test(valueEmittingObservable: Observable<string>) {
let wrapper = new Wrapper();
wrapper.taskDone$.subscribe(val => console.log("task done? ", val);
valueEmittingObservable.pipe(
// wrapper.wrappedSwitchMap(val => anObservableThatTakesAWhile(val))
wrapper.wrappedSwitchMap(val => of("foo").pipe(delay(5000)) // simulated
).subscribe(val => console.log("emitted value: ", val);
}
输出:
task done? false
(... 5 seconds delay ...)
task done? true
emitted value: foo
或者如果它的发射速度超过5秒:
task done? false
(... 1 second until next emit ...)
task done? false
(... 5 seconds delay ...)
task done? true
emitted value: foo