When the network connection is active, the observable will retry and repeat based on other observable signals

Sample snippet:

const networkConnected = new BehaviorSubject<boolean>(false);

setTimeout(networkConnected.next(true), 10000);

webSocket('ws://localhost:4949')
  .pipe(
    retryWhen(errors => errors.pipe(delay(10000), filter(() => networkConnected.value === true))),
    repeatWhen(completed => completed.pipe(delay(10000), filter(() => networkConnected.value === true))),
    tap(a => console.log('Connecting...'))
  ).subscribe(
    message=> console.info(message),
    error => console.error(error),
    () => console.warn('Completed'),
  );

I spent an hour searching but couldn't find anyone facing the same issue.

The goal is to reconnect a WebSocket whenever it drops connection, using retryWhen. Additionally, we use repeatWhen for cases where the WebSocket completes...

Now, I want to incorporate logic to ensure reconnection (retry/repeat) only happens when the internet connection is stable - indicated by the networkConnected observable being true. If it's false, retries/reconnections should wait until it becomes true.

Would utilizing zip or mergeMap work here? Alternatively, adding a timer that checks every second if the value is true with skipUntil.

If you have a better solution, please feel free to share 😊

Answer â„–1

To ensure that the websocket is only set up when network connectivity is established, a precondition can be put in place:

networkConnected
  .pipe(
    // ensuring that the websocket is not re-opened if the network is still connected
    distinctUntilChanged(),
    // opening the websocket when connected, otherwise waiting until connected
    switchMap(isConnected => isConnected ? openWebsocket() : empty())
  )
  .subscribe(
    message=> console.info(message),
    error => console.error(error),
    () => console.warn('Process completed successfully')
  );

openWebsocket = () => {
  return webSocket('ws://localhost:4949')
    .pipe(
      // handling websocket errors while network is connected
      retryWhen(errors => errors.pipe(delay(10000)),
      repeatWhen(completed => completed.pipe(delay(10000)),
      tap(a => console.log('Connecting to websocket...'))
    );
};

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

Angular input field with the ability to add and remove multiple options

Users can enter multiple emails to be added to a list, and they have the option to remove emails from the list. https://i.sstatic.net/vnHpJ.png ...

Passing arguments from nodes in Angular 2

I am looking to pass a parameter from a node, rather than a property. Here is an example of what I want: <!-- I want to use this: --> <navbar-comp> <items> <item label="Page 1" path="/page1" /> <item label="Page 2" pat ...

Error encountered when attempting to insert data into a PostgreSQL database using Node.js and Sequelize

I'm currently using the node sequelize library to handle data insertion in a postgress database. Below is the user model defined in the Users.ts file: export class User extends Sequelize.Model { public id!: number; public name: string; public ...

When attempting to compile Angular in production mode, errors may arise such as the Uncaught SyntaxError caused by an Unexpected token '<'

I encountered some errors in the console of my Angular 8 app. When I opened the browser window, it was blank and this error appeared: Uncaught SyntaxError: Unexpected token '<' https://i.sstatic.net/a16DD.png I tried running different ng bui ...

What is the overlay feature in Material-UI dialogs?

I recently started using the React-Redux Material-UI package found at http://www.material-ui.com/#/components/dialog My goal is to implement a grey overlay that blankets the entire dialog element, complete with a circular loading indicator after the user ...

Displaying exclusively distinct values in the selection box/dropdown menu

My goal is to retrieve data from the SQL server database and populate the corresponding fields on the frontend. While I am able to fetch the data, some fields in the response contain duplicate values in the dropdown menu. Here is an example of how my Compo ...

Vercel seems to be having trouble detecting TypeScript or the "@types/react" package when deploying a Next.js project

Suddenly, my deployment of Next.js to Vercel has hit a snag after the latest update and is now giving me trouble for not having @types/react AND typescript installed. Seems like you're attempting to utilize TypeScript but are missing essential package ...

Is it possible to incorporate a nested form in Angular reactive forms without utilizing an array?

this.parentForm = this._fb.group({ testControl1: [], testControl2: [], testChildForm1: this._fb.group({ testChildControl1: [], testChildControl2: [] }) )}; The parent form in the code above has two form controls and on ...

Looping through an array of objects with Angular 4's ngFor directive to dynamically display content

I am working with Angular 4 and I am attempting to iterate through an array of objects to present the data in Angular Material grid tiles. The code snippet from my HTML file (app.component.html) is as follows: <div class="list" *ngIf="listContacts == t ...

How can I call a global function in Angular 8?

Currently implementing Angular 8, my objective is to utilize downloaded SVG icons through a .js library. To achieve this, I have made the necessary additions to my .angular.json file: "scripts": [ "node_modules/csspatternlibrary3/js/site ...

Undefined output in Typescript recursion function

When working with the recursion function in TypeScript/JavaScript, I have encountered a tricky situation involving the 'this' context. Even though I attempted to use arrow functions to avoid context changes, I found that it still did not work as ...

Issues arising with utilizing Github for hosting Angular applications

After developing a site with Angular, everything was running smoothly on my local host. However, when I decided to host the site on GitHub, two errors appeared. You can access my site through this link: Here is a screenshot of the errors encountered [1]: ...

Utilizing Dynamic Class Names in Angular 7 with Typescript

In the process of developing an Angular 7 application, I have created a form component that is intended to be used for various entities. As part of this, I defined a variable route: {path: ':entity/create', component: FormComponent} While this ...

Can you explain the significance of using an exclamation mark after defining a variable in TypeScript?

As I delve into TypeScript in an effort to enhance my programming skills, I have encountered the use of exclamation marks when defining variables. An example of this can be seen in the following code snippet: protected _db!: CheckpointDB ...

Can a custom subscribe() method be implemented for Angular 2's http service?

Trying my hand at angular2, I discovered the necessity of using the subscribe() method to fetch the results from a get or post method: this.http.post(path, item).subscribe( (response: Response)=> {console.log(response)}, (error: any)=>{console.l ...

When restarting nginx, Angular fails to display the index page

On my VPS server, I have an application with the backend coded in node.js and the frontend in Angular. After restarting nginx, I encountered some issues where my API stopped working on HTTPS and only functioned on HTTP (previously, I was able to make requ ...

Typescript versus ES5: A comparison of Node.js server-side applications written in different languages

Note: When I mention regular JavaScript, I am referring to the ES5 version of JS. As I lay down the groundwork for a new project, my chosen tech stack consists of Node.js for the back-end with Angular2 for the front-end/client-side, and Gulp as the build ...

Creating an interface for a class instance through the implementation of a class constructor

I am working on an application where developers can specify which component they want to render a certain part. I need users to understand that they must implement an interface, but I'm struggling with correctly writing the typing. export interface I ...

Error in Typescript SPFx: The property 'news' is not found in the type 'Readonly<{}>'

Currently, I am working on developing a spfx react component to showcase an RSS feed in the browser. My prototype is functional in a test environment, however, as spfx utilizes TypeScript, I am encountering a type error that I am unsure how to resolve. Rs ...

Using Ionic/Angular ion-datetime with specific conditions

In my Ionic app, I have a datetime picker where users can select a time, but with one condition: If the hour is equal to '21', then the minutes must be set to '00' (not '30'). For all other hours, the minutes can be either &ap ...