RxJS: Disregard all but the last message while a webworker is cpu bound

Viewed 53

I have a web worker that crunches data when a message is received from the main thread. I've created a hot observable of those messages (using fromEvent). While the worker is crunching numbers, several messages will have come in telling the worker to re-crunch, I wanted to disregard all but the latest of those.

I've gotten something that works:

messages$.pipe(
  bufferTime(16),
  filter(x => x.length > 0),
  map(xs => xs[xs.length -1])
);

But it strikes me as suboptimal. I don't like, for example, that a bunch of blank arrays are emitted until I've filtered them out.

Is there a simpler approach I'm overlooking? Do I need to write a custom operator to get an optimal solution?

1 Answers

I think you can replace those 3 operators with debounceTime(0):

messages$.pipe(
  debounceTime(0)
)

several messages will have come in telling the worker to re-crunch

This approach presumes that these messages come synchronously.

Related