Creating an observable using a while loop: A step-by-step guide

I'm currently working on developing an Observable that actively queries an external service for updates and emits the new update when available:

this._loop = new Rx.Observable<TDL.Result>(subscriber =>
{
    let shouldLoop = true;

    while (shouldLoop)
    {
        if (!this._client)
            throw new Error("This client is not initialised.");

        const update = this._lib.receiveSync(this._client, 5);

        if (!update)
            continue;

        if (update._ === "error")
            this.emit("error", update);
        else
            this.emit("update", update);

        subscriber.next(update);
    }

    // The while loop prevents reaching this point, causing blocking when subscribing to this Observable

    // Cancellation logic
    return () =>
    {
        shouldLoop = false;
        this._loop = null;
    };
}).pipe(RxOp.publish()) as Rx.ConnectableObservable<TDL.Result>;

this._loopSubscription = this._loop.connect();

However, I've noticed that the subscribe function blocks the code when I call connect(). How can I modify this to make the subscription non-blocking?

Answer №1

Hey @martin, your solution worked like a charm. It's funny how sometimes the most obvious answer eludes us 😅

this._loop = new Rx.Observable<TDL.Result>(subscriber =>
{
    let shouldLoop = true;

    process.nextTick(() =>
    {
        while (shouldLoop)
        {
            if (!this._client)
                throw new Error("Looks like the client isn't initialized.");

            const update = this._lib.receiveSync(this._client, 5);

            if (!update)
                continue;

            if (update._ === "error")
                this.emit("error", update);
            else
                this.emit("update", update);

            subscriber.next(update);
        }
    });

    // logic for cancelling subscription
    return () =>
    {
        shouldLoop = false;
        this._loop = null;
    };
}).pipe(RxOp.publish()) as Rx.ConnectableObservable<TDL.Result>;

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 on toggling the button by clicking on the icon to turn it on or off

Within my angular application, I have implemented font icons alongside a toggle switch. Initially, the switch is in the ON state. The specific functionality desired is for clicking on an icon to change its color from white to red (this has been achieved) ...

What could be preventing the nesting of observables from functioning properly in Ionic-Angular?

Working with Observables has been an interesting experiment for me, but I'm facing an issue that I can't seem to resolve. While all the methods work perfectly fine when called outside the pipe, the problem arises when I nest them like this: creat ...

Manage sequential observables and await user input

I have a collection of items that I need to loop through in order to determine whether or not a modal dialog should be displayed to the user, and then pause the iteration until the user provides input. The items are stored within an observable as Observabl ...

Issue encountered in node_modules/@ngrx/store/src/models.d.ts(58,58): TypeScript error TS2304 - Unable to locate identifier 'unknown'

I am currently exploring the implementation of the REDUX Pattern in my upcoming Angular project, but I am facing issues with importing the necessary libraries. ERROR in node_modules/@ngrx/store/src/models.d.ts(58,58): error TS2304: Cannot find name &apo ...

Ionic app: refresher functionality works in browser but not on iOS home screen app

I am currently developing a Progressive Web App (PWA) using Ionic, and I have implemented an ion-refresher in the app: <ion-content> <ion-refresher slot="fixed" (ionRefresh)="refresh()"> <ion-refresher-content pullingIcon="lines">& ...

Is it necessary to compel subscribers to request data from Service again?

I have a straightforward setup, consisting of various elements and a singular service [StackBlitz]: https://i.sstatic.net/y6AFT.png Service @Injectable() export class Service { constructor(private http: HttpClient) {} saveItem(item: IItem): Observa ...

Cached images do not trigger the OnLoad event

Is there a way to monitor the load event of my images? Here's my current approach. export const Picture: FC<PictureProps> = ({ src, imgCls, picCls, lazy, alt: initialAlt, onLoad, onClick, style }) => { const alt = useMemo(() => initial ...

What is the reason for TypeScript not providing warnings for unrealistic conditions involving 'typeof' and 'in'?

The recent updates in version 4.9 highlighted the enhanced narrowing with 'in'. Intrigued by this, I decided to experiment with their example in a coding playground. Surprisingly, I discovered that seemingly impossible conditions involving typeof ...

Issue: Custom Object is returning an error stating that the property 'forEach' does not exist on type 'void'.ts(2339)

Within my code, I am dealing with a variable that can be either of type User or void. The dilemma arises when the code runs into an error message saying: Property 'forEach' does not exist on type 'void'.ts(2339). Despite trying various ...

What are the steps to styling a component with CSS Emotion?

I am facing an issue with using a theme with TypeScript in this component const buttonDisabled = css` color: ${({ theme }) => theme.color}; `; Is there a way to correctly type this component? Error: No overload matches this call. Overload 1 of 2, & ...

I'm working on an Angular2 project and I'm looking for a way to concatenate all my JavaScript files that were created from TypeScript in Gulp and then include them in my index

How can I concatenate all JavaScript files generated from typescript in my Angular2 project with Gulp, and then add them to my index.html file? I am using Angular2, typescript, and gulp, but currently, I am not concatenating the javascript files it genera ...

What is the best way to retain all checkbox selections from a form upon submission?

I have a batch of checkboxes that correspond to the profiles I intend to store in the database. HTML: <tr *ngFor="let profile of profiles | async"> <input type='checkbox' name="profiles" value='{{profile.id}}' ng-model=&apo ...

A specialized solution designed to avoid loops in references

Is there a method to create a general solution that can prevent circular variables in JavaScript? This solution should be effective for any level of depth or type of circular reference, not limited to the variable itself... So far I've come up with t ...

Error in Nestjs Swagger: UnhandledPromiseRejectionWarning - The property `prototype` cannot be destructed from an 'undefined' or 'null' object

Currently, I am in the process of developing a Nestjs REST API project and need to integrate swagger. For reference, I followed this repository: https://github.com/nestjs/nest/tree/master/sample/11-swagger However, during the setup, I encountered the foll ...

The Angular4 HttpClient is throwing an error stating that the type 'Observable<Observable<Object>>' cannot be assigned to the type 'Observable<boolean>'

Currently, I am utilizing the Angular 4 http client to fetch data from the server, but I am encountering an error that states: Type 'Observable<Observable<Object>>' is not assignable to type 'Observable<boolean>'. ...

The functionality of Angular 6 Material Nested Tree is disrupted when attempting to use dynamic data

In Angular 6, I am utilizing mat-tree along with mat-nested-tree-node. My objective is to dynamically load the data when the user toggles the expand icon. Attempting to apply the dynamic data concept from the Flat Tree example provided in Material Example ...

Is it possible to retrieve 2 arguments within a function in a non-sequential manner?

Let's say there is a function with arguments A, B, C, D, and E. Function(A, B, C, D, E) However, not all arguments are needed all the time. For instance, only A and C are needed in some cases. Currently, I would have to call the function like this: Fu ...

Tips for populating a dropdown list with data from the backend and selecting the desired value using Angular

I am currently working on an Angular 8 application that utilizes Material design. My goal is to populate a dropdown list with data retrieved from the backend. The API call code snippet is as follows: returnQrCodes$ : Observable<QRCodeDefinitionSelect ...

TypeDoc fails to generate documentation for an Express JS API and displays no information

As I strive to document my Express JS API using TypeDoc, I am encountering an issue where the generated documentation is quite empty. https://i.sstatic.net/LRhOE.png This outlines my API file structure: https://i.sstatic.net/6zuXQ.png Below is a snippet ...

What is the approach to forming a Promise in TypeScript by employing a union type?

Thank you in advance for your help. I am new to TypeScript and I have encountered an issue with a piece of code. I am attempting to wrap a union type into a Promise and return it, but I am unsure how to do it correctly. export interface Bar { foo: number ...