typescript - rxjs:弹出窗口流
问题描述
我必须一个接一个地向用户显示 N 个引导弹出窗口。我目前确实有一个消息流要显示在每个弹出窗口中。如果我进行简单的订阅并显示消息,它不会等待用户关闭弹出窗口并show('modal')
多次调用或更改消息以仅向用户显示最后一个消息。
一个疯狂的想法是使用运算符为每个通知添加延迟,debounce
并希望用户的大脑与您的延迟同步。
我一直在考虑为接收端创建一个带有回调函数的通知流,让我知道通知是否已被使用。
export class CallbackNotification<T> {
parameter : T;
callbackFunction: () => any;
}
export function notifyAndMoveNext<T>(source: Observable<T>) : Observable<CallbackNotification<T>> {
let notifications = new BehaviorSubject<any>(0);
return
zip(source, notifications)
.pipe(map(([a, n]) => <CallbackNotification<T>> {
parameter = a,
callbackFunction = () => notifications.next(0)
}));
}
那么我可以简单地做
notifyAndMoveNext(myMessagesObservable).subscribe(x => { this.currentNotification = x.callbackFunction; showModal(x.parameter); });
并在弹出窗口的按钮事件处理程序处
this.currentNotification();
以上不适用于共享订阅(publish 和 refCount),还有什么其他人认为我没有看到的错误吗?你们有什么替代方案吗?
解决方案
解决方案是将每条通知消息变成一个 Observable(或 Promise),直到用户关闭通知才完成。然后只需使用concatMap
. concatMap 将等待上一个消息完成,然后再订阅下一个
这是一个例子:
const showNotification = (notification) => {
// return a "cold" observable using RxJS defer function
// so that the notification is not shown until
// we are subscribed
return defer(() => new Promise(resolve => {
// when popup calls this.currentNotification() resolve the promise
this.currentNotification = resolve;
showModal(notification);
}));
};
notifications.pipe(concatMap(showNotification)).subscribe();