Debounce and buffer an rxjs subscription

自作多情 提交于 2019-12-24 01:01:36

问题


I have a message queue processor that feeds messages to a service...

q.on("message", (m) => {
  service.create(m)
    .then(() => m.ack())
    .catch(() => n.nack())
})

The service uses an RxJS Observable and subscription to debounceTime() those requests.

class Service {
  constructor() {
    this.subject = new Subject()
    this.subject.debounceTime(1000)
      .subscribe(({ req, resolve, reject }) =>
        someOtherService.doWork(req)
          .then(() => resolve())
          .catch(() => reject())
      )
  }

  create(req) {
    return new Promise((resolve, reject) =>
      this.subject.next({
        req,
        resolve,
        reject
      })
    )
  }
}

The issue is that only the debounced request gets ackd/nackd. How can I ensure that the subscription also resolves/rejects the other requests? bufferTime() gets me a part of the way there, but it does not reset the timeout duration on each call to next().


回答1:


The debounceTime operator that you are currently using can be used to create an observable that can notify buffer of when the current buffer should be closed.

Then, buffer will emit an array of the messages that were received whilst debouncing and you can do with them whatever you want:

this.subject = new Subject();
const closingNotifier = this.subject.debounceTime(1000);
this.subject.buffer(closingNotifier).subscribe(messages => {
  const last = messages.length - 1;
  messages.forEach(({ req, resolve, reject }, index) => {
    if (index === last) {
      /* whatever you are doing, now, with the debounced message */
    } else {
      /* whatever you need to do with the ignored messages */
    }
  });
});


来源:https://stackoverflow.com/questions/50515357/debounce-and-buffer-an-rxjs-subscription

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!