Is it possible to capture and retain data, then transmit it x seconds after the initial data capture?

RxJS 4:

I am attempting to capture and emit values after a certain interval of time has passed since the first value was received from a websocket. Essentially, once the first value is received, a timer will start to store subsequent incoming values and then emit them after x seconds. Once the values are emitted, the timer stops and no more values are emitted until a new one comes in from the websocket, at which point the cycle begins again.

The motivation behind this setup is that currently in my application, data is being emitted almost constantly (at a nanosecond level) via the websocket, impacting performance. I want to aggregate as many values as possible over a set amount of time, then emit them together for batch processing.

Despite my efforts, the code I have attempted doesn't seem to be working as intended.

         public testObs = new Observable<any>();
         public bufferStarted = false;
         private subject = new Subject<any>();

         webSocket.onmessage = ((event: any) => {
            this.subject.next(event.data);
            if(!bufferStarted) {
                bufferStarted = true;

                // Start the buffer now
                const startInterval = Observable.timer();

                // Emit value after 1s and close buffer
                const closingInterval = val => {
                    console.log(`Buffer is open! Emitting value after 1s`)
                    bufferStarted = false;
                    return Observable.interval(1000);
                }
                this.testObs = this.subject.bufferToggle(startInterval, closingInterval);
             }
         }

In the component, I subscribe to

testObs.subscribe((e) => ... )
. For example, if a value is sent through the websocket, triggering a timer to open a buffer for 1 second. Within that second, 50 additional values are received. I expected to receive an array of 51 values in the component. However, the observable appears to be undefined. Any help would be greatly appreciated.

Answer №1

bufferTime could be a great option for your situation.
It allows you to group emitted items within a specified time frame. Keep in mind that it will also emit an empty array if no items are emitted from the source. You can use filter to exclude the empty array if needed.

For example:

// assuming a web socket stream
ws$;

const notEmpty = arr => Boolean(arr.length);

const grouped$ = ws$.pipe(bufferTime(1000), filter(notEmpty));

grouped$.subscribe(group => {
// 'group' is an array of items from ws$
// add your logic here
});

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

No declaration file was located for the module '@handsontable/react' despite the presence of a 'd.ts' file

Embarking on a fresh project using vite+react+ts+swc by executing the command below as per the vite documentation. npm create vite@latest -- --template react-swc-ts Additionally, I integrated the handsontable library into my setup with the following comm ...

Using Angular to create a dynamic form with looping inputs that reactively responds to user

I need to implement reactive form validation for a form that has dynamic inputs created through looping data: This is what my form builder setup would be like : constructor(private formBuilder: FormBuilder) { this.userForm = this.formBuilder.group({ ...

Clicking on a single checkbox causes the entire input to become deactivated due to the way the system is

I'm encountering a puzzling issue that has me feeling like I know the solution, yet I don't. I set "State" to [checked]. The problem arises when, upon turning it into a map and clicking just one checkbox, the entire selection is clicked. To addre ...

Exploring Ionic 2: Utilizing Service and modalCtrl for enhanced functionality

I am relatively new to using Ionic 2. Recently, I created a service that contains all my filters (ModalCtrl) with custom search input and checkboxes. I am passing parameters between them but I am unsure of how to keep the service active and waiting for the ...

Real-time database functionality in MySQL akin to Firebase's capabilities

Recently, I've been experimenting with Angular4 and Firebase in hopes of finding a solution for a new, challenging project. While I've been able to make it work for simpler tasks, I'm struggling with Firebase's JSON data structure which ...

How can we import the entire Jasmine library using CucumberJS?

I am currently trying to implement unit testing using Jasmine and CucumberJS in my Angular v9 application. I have followed the tutorial provided by cucumber.io to set up cucumber as the default runner. However, I am facing difficulties in using Jasmine met ...

What are the best techniques for streamlining nested objects with Zod.js?

As a newcomer to zod.js, I have found that the DataSchema function is extremely helpful in verifying API data types and simplifying the API response easily. However, I'm curious if there is a way to streamline the data transformation process for myEx ...

What causes the cursor in an editable div to automatically move to the front of the div?

<div className="min-w-[600px] min-h-[36.8px]" > <div id={`editableDiv-${Object.keys(item)}-${index}`} className="p-3" contentEditable suppressContentEditableWarning onInput={(e) => onChange(e)} > ...

What could be causing my Angular2 component to not properly use my template?

I have two components that I am working with. The first component is: import {Component} from 'angular2/angular2'; import {Navbar} from './navbar'; @Component({ selector: 'app' template: `<div class="col-md-12"> ...

Transitioning React components organized in groups to TypeScript

As I transition my react project to incorporate typescript, one challenge I encountered was adjusting the file structure. In its simplified form, here is how the original js project's file structure looked like: src components index.js inputs butt ...

Tips for organizing JSON Objects in TypeScript

I'm looking to sort a JSON object within my Angular application. The JSON object I'm working with appears as follows: {"9 - ABCDEF":{"isSucceeded":true}, "18 - Remote Software Update":{"isSucceeded":true,}, "4 - n.a."{"isSucceeded":true,}} My ...

Expanding the Warnings of React.Component

When I create a new class by extending React.Component in the following manner: export default class App extends React.Component<any, any > { constructor (props: React.ReactPropTypes) { super(props); } // other code } I encountere ...

Utilizing the adapter design pattern in Angular with TypeScript for enhancing a reactive form implementation

I've been struggling to understand how to implement the adapter pattern in Angular6. Despite reading numerous articles and tutorials, I still can't quite grasp the concept. Could someone provide some insights on this topic? Essentially, I have a ...

Leverage the generic types of an extended interface to simplify the creation of a shorthand type

Attempting to streamline my action shorthand that interacts with AsyncActionCreators. A function has been crafted to accept a React dispatch: Dispatch<T> parameter: const fetchProfileAction = actionCreator.async<void, Profile, any>('FETC ...

gulp-webpack is unable to locate node packages

Currently working on developing a modern Angular application. I have opted to use gulp-webpack for quick development builds. To handle my TypeScript bundling and node modules dependencies, I am relying on webpack. However, it seems that gulp-webpack is no ...

Exploring disparities between the Client SDK and Admin SDK in conducting firestore queries

I am encountering difficulties with my query while running it in Firebase Functions. It functions perfectly on the client side, but fails to work in Functions. I am curious if there is a way to modify it to function with Admin SDK as well. Am I making any ...

Ways to indicate a checkbox as selected within angular version 4

I'm a complete beginner in Angular 2 and I need to be able to check checkboxes when a button is clicked. I have multiple checkboxes generated in a loop like this: <tr *ngFor="let roleObj of roleNameList"> <td> <input ty ...

Is it worth incorporating dependency injection for injecting classes?

In the AngularJS days, factory was commonly used to inject classes instead of instances. This practice continues in Angular 2: {provide: MyClass, useFactory: () => { return MyClass }} ... constructor(MyClass) { let instance = new MyClass(); } Howe ...

Testing the MatDialog Component

Currently, I am in the process of creating a unit test for my confirmation modal that relies on MatDialog. The initial test I have set up is a simple one to ensure that the component is successfully created. Below is the code snippet from my spec file: im ...

Drawer in Material-UI has whitespace remaining at the corners due to its rounded edges

While using the Material UI drawer, I attempted to round the corners using CSS: style={{ borderRadius: "25px", backgroundColor: "red", overflow: "hidden", padding: "300px" }} Although it somewhat works, the corners appear white instea ...