Is there a way to address the sporadic behavior of rxjs combineLatest when used in conjunction with ReplaySubject

My current struggle lies within this particular example:

const r1 = new ReplaySubject(2);
const r2 = new ReplaySubject(2);
r1.next('r1.1');
r1.next('r1.2');
r2.next('r2.1');

combineLatest([r1, r2]).subscribe(console.log);  // -> ["r1.2", "r2.1"]
combineLatest([r2, r1]).subscribe(console.log);  // -> ["r2.1", "r1.1"] -> ["r2.1", "r1.2"]

// r1.1 ----> r1.2 --------
// -------------------> r2.1

After much contemplation, I find that my understanding may be hindered by the application's execution rather than the function's given specifications to produce the latest combinations.

Nevertheless, my quest is for a functionality similar to "combineEvery" that consistently outputs the second value. How might I go about implementing this?

// r1.1 ----> r1.2   
// -------------------> r2.1
// -------------------------------> r3.1

[r1.1, r2.1, r3.1] -> [r1.2, r2.1, r3.1]

Answer №1

The behavior of the code snippet above is a result of how the combineLatest function operates. It waits to emit values until it has received at least one value from each observable. This is achieved by keeping track of the initial emissions from the inner observables and only emitting values once the counter matches the total count of all observables.

When using ReplaySubject, only the last element in the array of ReplaySubject instances will have all its buffered values emitted immediately. This is because the emissions from the other instances occur before the counter reaches the total count of all observables.

const r1 = new ReplaySubject(3);
const r2 = new ReplaySubject(3);
const r3 = new ReplaySubject(3);
r1.next('r1.1');
r1.next('r1.2');
r1.next('r1.3');
r2.next('r2.1');
r2.next('r2.2');
r3.next('r3.1');
combineLatest([r1, r2, r3]).subscribe(console.log);  // -> ["r1.3", "r2.2", "r3.1"] 

To achieve the desired outcome, one approach is to prime the values with the first result and then introduce an artificial delay using the timer operator. Subscribing to the remaining emissions after this setup allows for the retrieval of the expected values.

combineLatest([
  concat(r1.pipe(first()), timer(0).pipe(switchMap(() => r1.pipe(skip(1)))),
  concat(r2.pipe(first()), timer(0).pipe(switchMap(() => r2.pipe(skip(1)))),
  concat(r3.pipe(first()), timer(0).pipe(switchMap(() => r3.pipe(skip(1))))
]).subscribe(console.log);  
// Using the values from the previous example, the following output is expected:
// ["r1.1", "r2.1", "r3.1"]
// ["r1.2", "r2.1", "r3.1"]
// ["r1.3", "r2.1", "r3.1"]
// ["r1.3", "r2.2", "r3.1"]

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

What is the best way to call a method of a JavaScript object after calling a different method?

Upon frequently encountering this jQuery code snippet, I decided to simplify it into one level action as illustrated in the following code. function $(id) { var $ = document.getElementById(id); $.action1 = function() { }; return $; } Now ...

Vue - Syntax error: Unexpected token, expecting "}."

I recently started working with Vue and have encountered a simple component issue. Sometimes, when I run npm run serve or save a file that is already being served, I receive the following error message: E:\Development\website\app>npm run ...

Adding a combination of HTML and Javascript to an element can result in unexpected behavior

http://jsfiddle.net/PeKdr/ Encountering an issue when having a JavaScript variable that contains both HTML and JavaScript, resulting in unexpected behavior in the output window. Neither of the buttons - one triggering the function appendTheString() or the ...

What is the method for submitting a form when a change occurs?

This inquiry is focused on the Captive Network Assistant. I attempted to utilize plain JavaScript, <form action=""> <select name="test" onchange="this.form.submit()"> <option value="1">1</option> <option val ...

ng filtering with a controller-defined scope

I am currently working on a webpage with AngularJS and I am looking to implement some filters on the site. Here is the HTML code I have: <div ng-repeat="data in datas | filter:{area:course} | filter:{subject:subFilter} | filter:{city:cityFilter}"> ...

A guide on efficiently inserting multiple rows containing JSON data into a MySQL database simultaneously using node.js

I'm facing an issue with inserting multiple values into columns simultaneously. Let's say I have JSON data consisting of two rows of information, and I want to insert both rows into my table at one go. My attempt looks like this: var data = [&apo ...

What could be the reason for the unavailability of this.state in this particular situation?

In my component, I have defined the following functions: constructor(MyProps: Readonly<MyProps>){ super(MyProps); this.state = {suppliers: [], supplierId:0, supplierName:''}; this.addSupplier.bind(this); } addSupplier(){ ...

How can I extract the text from a textarea in react-bootstrap and pass it to a function when a button is clicked?

Below is the React-Bootstrap code that I am working with: <Form> <Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1"> <Form.Label>Example textarea</Form.Label> <Form.Control as=&quo ...

Encountering issue while resolving flux/utils in webpack

My TypeScript OS project is in the process of being migrated to webpack, Unfortunately, I am currently facing a build error: ERROR in ./src/store/GigaStore.ts Module not found: Error: Cannot resolve module 'flux/utils' in /home/erfangc/GigaGrid ...

Communicate through PHP and JavaScript chat to display HTML content in the chat window

I have been attempting to display HTML output in the chat window but instead, it is showing the HTML code. Here are the two files involved in the chat system: chat.js `function chatHeartbeat(){ var itemsfound = 0; if (windowFocus == false) { var ...

JavaScript Game Timer

I am working on a countdown timer where I have set the variable seconds to 10. If the seconds reach zero, I want to add 2 seconds to it and stop the program from looping. Can someone please assist me with this? var isWaiting = false; var isRunning = fal ...

Create a custom CSS style to replace the default jQuery hide() function

HTML <div class="adm-input" <?php if(!empty($admin_fee) || $admin_fee != "") echo "style='display:block'"; ?> id="fees-input"> <label>Admission Fees(<i class="fa fa-inr"></i>)</label> <div class="in ...

Adding data to a defaultContent JSON column in JQuery DataTable using JavaScript

I am working with a dynamic jQuery data table. The final column in my table allows users to delete rows, but I am having trouble passing the itemId value to the specified function within the button's onClick attribute. Here is the code I have tried s ...

What is the best way to extract the value from a resolved Promise?

Currently, I am attempting to read a file uploaded by the user and convert it into a String using two functions. The first function is handleFileInput: handleFileInput(event){ setTimeOut(async()=>{ let abcd= await this.convertFileToString(this.fi ...

The issue with hiding and showing elements using JavaScript during drag and drop functionality

In my code, I have two boxes with IDs box1 and box2, These boxes can be dragged and dropped into the boxleft element, Upon dropping them, the background image is removed and only the name appears in the box, My issue is that when loading values into box ...

What is the proper method for utilizing an object as a dependency when using useEffect?

Currently, I am in the process of developing a react hook that takes in a query object. export function useMyQuery(query: QueryObjectType) { React.useEffect(executeQuery, [ query ]); // ... } Unfortunately, whenever my hook is called during a re- ...

Update the dropdown menu based on the revised time

I need to create a PHP site and JavaScript function that changes a dropdown menu based on specific time intervals, such as 7:00-8:00 (id530), 13:00-15:00 (id1330), or 20:00-03:00 (id2130). For example, if the time is 7:31, the dropdown menu should display/ ...

Are there any Android applications specifically designed for editing Typescript files?

While this may not be a typical programming inquiry, I have phrased it in a binary manner in hopes of meeting the criteria. I have been utilizing Quoda on my Android device and have encountered the need to edit .ts / Typescript files, which the app does n ...

Angular Pagination: A Detailed Guide

My goal is to paginate 7 results using a custom pagination tag I created: <pagination ng-model="currentPage" total-items="array.length" max-size="maxSize" boundary-links="true"> </paginatio ...

Quarterly Date Selection Tool with jQuery

I attempted to utilize the Quarter datepicker from: http://jsfiddle.net/4mwk0d5L/1/ Every time I execute the code, I encounter this problem: Cannot set property 'qtrs' of undefined. I copied exactly what was in the jsfiddle, and included the sam ...