Cease the interval once the array is devoid of elements

I'm currently working on simulating typing effects for incoming server messages by adding an interval to the output.

Here's what I have so far:

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

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

However, I'm looking to stop the interval once my 'messages' array is empty. I've been trying to implement .TakeWhile without much success. Can anyone offer assistance with this issue?

Thank you in advance.

Answer №1

To implement takeWhile effectively, you can utilize the following code snippet:

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

I have created a demonstration on stackblitz for your reference: https://stackblitz.com/edit/typescript-sq6wxb?file=index.ts

Answer №2

It seems like the issue you're facing is that stream continues to emit even when messages is empty.

To resolve this, you can utilize the takeWhile operator in your stream:

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

When messages becomes empty, it will return undefined, which evaluates to false. This is why using takeWhile(Boolean) will help complete the stream accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to retrieving specific attributes from an object within an array of objects using Angular Typescript

As an example, if we consider a sample JSON data retrieved from the JSONPlaceholder website at https://jsonplaceholder.typicode.com/users. [ { "id": 1, "name": "Leanne Graham", "username": "Bret&q ...

How to implement div scrolling on button click using Angular 4

Is there a way to make the contents of a div scroll to the left when one button is clicked and to the right when another button is clicked? I've tried using ScrollLeft, but it doesn't seem to be working... Here's the HTML code: <button ...

Issue with passing props to child component in React due to TypeScript error

In the process of developing an expense tracker app using react and typescript. expense_type.ts export type IState = { id : number, text : string, amount : number } export type IinitialStateType = { transactions : IState[] } expor ...

The Angular ViewportScroller feature appears to be malfunctioning in the latest release of Angular,

TestComponent.ts export class TestComponent implements OnInit, AfterViewInit { constructor( private scroller: ViewportScroller, ) {} scrollToAnchor() { this.scroller.scrollToAnchor('123456789'); } } HTM ...

Display the map using the fancybox feature

I have added fancybox to my view. When I try to open it, I want to display a map on it. Below is the div for fancybox: <div id="markers_map" style="display:none"> <div id="map_screen"> <div class="clear"></div> </div&g ...

Binary encounters an issue: Error - Module failed to self-register

Binary file saved to the specified directory Caching binary for future use [email protected] during postinstall node script execution. The system attempted to locate the relevant binary but encountered an error: Module did not self-register. This iss ...

Utilizing data from the home component in another component: A guide

Here is the code I am working with, showcasing how to utilize (this.categoryType) in another component: getCategoryDetails(){ return this.http.get('ip/ramu/api/api/…') .map((res:Response) => res.json()); } The above code snippet is utilize ...

Using RxJS and the combineLatest function can be hit or miss in terms of reliability

When you call this function multiple times with the values of observables obs1 and obs2 being the same each time, the returned array may not always be the same. getUniqueProducts(obs1: Observable<any>, obs2: Observable<any>): Observable<any& ...

Leveraging WebStorm's TypeScript support in conjunction with node_modules

Attempting to set up a TypeScript project in WebStorm to import a Node.js module has been a struggle. I made sure to download the necessary TypeScript definition in settings and specified --module commonjs in the compiler settings. However, I keep running ...

Encountering build error ts2307 while using Angular 6 with npm: Module "ngx-loading-mask" not found

After exhausting all my search efforts on Google, I am stuck at a roadblock while upgrading from version 5.x to 6.x. My npm install runs smoothly with just 2 WARNS that are not causing any problems. But there are two strange issues that I can't seem ...

Implementing the "$store" property within Vue components

Click here for a guide on how to type the $store property. Unfortunately, I've been encountering issues with it. In my Vue 2 project created using vue-cliI, I included a vuex.d.ts file in ./src directory but the $store property in my components still ...

Using `@HostListener` with `e: TouchEvent` is known to trigger a crash in Firefox, displaying the error message "ReferenceError: TouchEvent is not defined."

When using @HostListener with the event parameter explicitly typed as a TouchEvent, it triggers Firefox to crash and display an error message: ReferenceError: TouchEvent is not defined. This can be illustrated with the following example: @HostListener ...

Tips for preventing the ngbTypeahead input field from automatically opening when focused until all data is fully mapped

When clicking on the input field, I want the typeahead feature to display the first 5 results. I have created a solution based on the ngbTypeahead documentation. app.component.html <div class="form-group g-0 mb-3"> <input id="typ ...

A TypeScript class utilizing a static variable with the singleton design pattern

I have a query regarding the most effective way to code this scenario: Within a class, I require a static variable that is accessible throughout the entire project: connection Singleton without namespace: class Broker { static connection: Connection = u ...

Running an ESNext file from the terminal: A step-by-step guide

Recently, I delved into the world of TypeScript and developed an SDK. Here's a snippet from my .tsconfig file that outlines some of the settings: { "compilerOptions": { "moduleResolution": "node", "experimentalDecorators": true, "module ...

Troubleshooting Date library timezone problems in Typescript locale

The TZ variable is automatically set by Node as an environment variable. When using new Date(); in TypeScript, the date returned is in GMT+0000 even though the code is being executed on a machine with a timezone of GMT+0530. I attempted to print out conso ...

What is the best way to programmatically generate a service within Angular?

Is there a way to dynamically create services at runtime using a string name (like reflection)? For example: let myService = new window[myClassName](myParams); Alternatively, you could try: let myService = Object.create(window[myClassName].prototype); m ...

Leverage the useRef hook with React Draggable functionality

Having recently delved into coding, I find myself navigating the world of Typescript and React for the first time. My current challenge involves creating a draggable modal in React that adjusts its boundaries upon window resize to ensure it always stays wi ...

Obtaining information from an API using Angular

I am currently working on extracting data from various API's and I am encountering some difficulties. The initial part is functioning correctly, with the code provided below : ngOnInit(): void { this.http.get('http://.../api/getData?table=ge ...

How to retrieve the total count of dynamically inserted list items within an unordered list in Angular

Is there a way to calculate the number of dynamically added list items within a ul element? I need this information to adjust the width of a queue element based on the number of list items with a formula like [style.width.px]="numberOfLi * 50". Any sugge ...