What could be causing the second switchMap to be triggered repeatedly upon subscription?

Check out the code snippet below for reproducing the issue:

import { defer, BehaviorSubject, of } from "rxjs";
import { shareReplay, switchMap } from "rxjs/operators";

const oneRandomNumber = defer(() => of(Math.floor(Math.random() * 20)));

const cache = { key: oneRandomNumber.pipe(shareReplay(1)) };

export const swr = () =>
  new BehaviorSubject(null).pipe(
    switchMap(() => cache.key),
    switchMap(number => {
      console.log(number); // WHY DOES THIS EXECUTE SO MANY TIMES?!
      return cache.key;
    })
  );

swr().subscribe();

demo

The expected behavior is to only see one number logged, not hundreds.

The issue can be resolved by undertaking any of the following actions:

  • eliminate shareReplay(1)
  • bypass using the cache object and directly use
    oneRandomNumber.pipe(shareReplay(1))
  • limit the usage of switchMap twice

However, all those elements are necessary in my final code implementation.

Answer №1

It appears that your code is functioning as intended. The use of `shareReplay` in this code causes the observable to be replayed each time it is used, which explains the behavior you are seeing. However, the presence of two `switchMap` operators without an endpoint leads to an infinite loop of replaying and ultimately results in chaos.

The issue lies in the fact that the first `switchMap` operator lacks an endpoint, such as `take(1)` or a similar mechanism.

Contrary to what you may have thought, adjusting the buffer size will not resolve this problem. Buffer sizes only impact multiple subscriptions, not the repeated usage of observables in this scenario.

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

Enhancing user experience with jquery autocomplete matching

Currently utilizing the JQuery Autocomplete plugin. It seems that the default behavior is to match from the start, so "foo" matches "fool", but not "bufoon". I am seeking a way for matching to happen anywhere in the text and also in a case-insensitive man ...

Error: Jest encounters an unexpected token 'export' when using Material UI

While working on my React project and trying to import { Button } from @material-ui/core using Jest, I encountered a strange issue. The error message suggested adding @material-ui to the transformIgnorePatterns, but that didn't resolve the problem. T ...

tips for selecting various API requests based on the selected drop down menu choice

Hey there! I'm looking to enhance my login page by adding a feature that allows users to select from a dropdown menu with different options. Each option will be linked to a specific API, and based on the API response, the user's ability to log in ...

View real-time data in Vuejs 3 as it executes

I am currently working on a form that populates a table with data retrieved from a Laravel API. I am using Vue.js 3 and Composition API to build my entire application. When the button is clicked, I want the table to be filled with data from the form. The b ...

What could be the reason why the initial console.log is failing to print?

Apologies for the oversight. The !== was a mistake that slipped past me before posting. Thank you for your understanding. I am a beginner in Javascript. I have written this function with winston: function setlogger(log_level = "warn", logfile, scree ...

"Navigate through the page by scrolling with your mouse all the way to 100

Is it possible to trigger an action when a user starts scrolling using the mousewheel? I've searched online but all I found was information on 100% scroll on click. I want the window to automatically be scrolled down to 100% as soon as the user starts ...

Discover the method for two form fields to submit data to a distant page, located two pages away

Currently, I'm trying to figure out the best approach for having two fields submitted to a page that is located two pages away. To provide more context, let me elaborate on the situation. On the initial page, there will be two fields - workshop title ...

What is the mechanism behind range traversal in Javascript?

Exploring the createRange() function and related constructs in Javascript has sparked my curiosity about its practical applications. During my search, I stumbled upon an interesting application called "" that allows users to highlight text with mouse clic ...

"Encountering an error in Vue.js when trying to dynamically access nested arrays: push function not

My goal is to have two buttons displayed when a user uploads data: one for old products and one for new products. When the user clicks on either button, the corresponding products will be uploaded as 'old_product' or 'new_product'. Howe ...

"Learn how to update an existing table row and populate its cells with JSON data retrieved from a successful AJAX request without creating a

Currently, I am utilizing CouchCMS. The platform offers a feature known as repeatable regions which essentially generates tables to showcase recurring content. The defined repeatable region looks like this: <cms:repeatable name="item_detail" ...

Understanding the use of "el" in a function parameter in Vue Js

I am new to VueJS, so please be patient with me. I am trying to code a function that will scroll to an element with a specific ID when a "?" is used in the URL. I want it to have the same effect as demonstrated here. My assignment requires me to follow a ...

Guide to extracting information from a Node.js http get call

I am currently working on a function to handle http get requests, but I keep running into issues where my data seems to disappear. Since I am relatively new to Node.js, I would greatly appreciate any assistance. function fetchData(){ var http = requir ...

TypeScript: creating an interface property that relies on the value of another

Is it feasible to have an interface property that relies on another? For instance, consider the following: const object = { foo: 'hello', bar: { hello: '123', }, } I wish to ensure that the key in bar corresponds to the value of f ...

Generate a random number to select a song file in Javascript: (Math.floor(Math.random() * songs) + 1) + '.mp3'

My current JavaScript code selects a random song from the assets/music folder and plays it: audio.src = path + 'assets/music/'+(Math.floor(Math.random() * songs) + 1)+'.mp3' However, I've noticed that sometimes the same trac ...

Information sent by the Firefox TCP socket using the socket.send() method cannot be retrieved until the socket is closed

I am experiencing an issue while trying to send data from Firefox to a Java desktop application. My Java class functions as a server, and the Firefox script acts as a client. When I test it using another Java class called client.java, the data is successfu ...

Tips on accessing the v-model value with a parameter in VUE

Looking to access the v-model value using a parameter, I attempted the following code: <template> <div v-for="(item, idx) in data"> <input :id="item" :v-model="item"></input> <button @click=&q ...

Refreshing an external file in Node.js at regular intervals

Seeking guidance on loading external files in node. I'm currently working with an external JSON file that houses some configuration settings, and this file gets updated by an outside process every 10 minutes. How can I automate the reloading of this ...

How to Delete Elements from an ngList Array in Angular

I encountered an issue while utilizing ngList in a text box to exchange data with my server. The problem arises when I attempt to delete items from the generated array directly, as it does not reflect the changes in the input field. The main concern is th ...

The v-model in the Vue data() object input is not functioning properly and requires a page refresh to work correctly

Explaining this situation is quite challenging, so I created a video to demonstrate what's happening: https://www.youtube.com/watch?v=md0FWeRhVkE To break it down: A new account can be created by a user. Upon creation, the user is automatically log ...

Tips for structuring route dependencies in Node.js and Express

Although I have a good grasp of exporting routes to an index.js file, my struggle lies in properly referencing external route dependencies without having to copy them to the top of the file. For instance, if I have the main entry point of the program (ind ...