Stop interval when empty array

179 views Asked by At

I'm receiving a bunch of Messages from serverside and I wanna fake the typing by adding a interval to the pipe.

I'm doing this for now:

const stream = interval(1000)
  .pipe(
  map((): Message => {
    return messages.pop();
  })
);

this.feed = merge(
  stream,
  this.local
).pipe(
  scan((acc, x) => [...acc, x], [])
);

But I want it to stop the interval once my array 'messages' is empty, could someone help me please? I have been trying to implement .TakeWhile with no success.

Thanks in advance.

2

There are 2 answers

0
Boris Lobanov On BEST ANSWER

takeWhile works fine, you'd need something like this:

const stream = interval(1000)   
  .pipe(
     takeWhile(() => messages.length > 0),
     map(() => messages.pop()),   
  );

I made a little example on stackblitz, I hope you can work this into your application: https://stackblitz.com/edit/typescript-sq6wxb?file=index.ts

0
martin On

So your problem is that stream keeps emitting even after messages is empty.

You can use takeWhile to complete the stream:

const stream = interval(1000).pipe(
  map((): Message => messages.pop()),
  takeWhile(Boolean),
);

When messages is empty it returns undefined which is false when turned to boolean so takeWhile(Boolean) will complete the stream.