audiodude
audiodude

Reputation: 2810

How do I write this RxJs code so that the delay between outputs is dynamic?

I'm writing a game, and there is an event queue. I've used RxJs to modify a Subject so that it's "rate-limited", ie it outputs a new value only every 2500 seconds:

  this.q = new Subject();
  this.q
  .pipe(
    concatMap(item => of(item).pipe(
      concat(
        of('ignored').pipe(
          delay(2500),
          ignoreElements()
        )
      )
    ))
  )
  .subscribe(evt => {
    this.processEvent(evt);
  });

The networking code calls this.q.next(evt) when it receives a message from the server.

This is working for static rate limiting by a constant amount. But I realize that some events should have shorter delays before the next event and especially some should have much longer delays, in order to let the UI animate something or let the user digest the information.

Is there a way to change that constant 2500 into a value that is pulled off of the item, like item.delay?

Thanks!

Upvotes: 0

Views: 47

Answers (1)

Rafi Henig
Rafi Henig

Reputation: 6422

You might want to try the following approach:

  this.q
  .pipe(
      concatMap(item => of(item).pipe(delay(item.delay))))
    )
  )
  .subscribe();

Upvotes: 1

Related Questions