What techniques can I employ to ensure that withLatestFrom() effectively interacts with itself?

In my program, I have an intermediate stream that is connected to a source, but it can also trigger events from other sources (such as user input). In another part of my code, there is a derived stream that needs to compare new data from the intermediate with the last value of the source. This is the snippet of code that handles this scenario:

const source = new Rx.Subject;
const derived = new Rx.Subject;
derived.subscribe( () => console.log( "derived" ) );
const intermediate = new Rx.Subject;

// The reason for having the "intermediate" stream is that sometimes it triggers on its own:
source.subscribe( intermediate );

intermediate
    .withLatestFrom( source )
    .subscribe( derived );

source.next();
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.3/Rx.min.js"></script>

The issue here is that the "derived" message is never displayed (the first event in the source is being ignored). How can I create a stream that retrieves the last value of the source for every message from the intermediate stream, even if the source is currently propagating?

Answer №1

From what I gather, there is a flow involving a source stream, followed by an intermediate stream that subscribes to and emits all items from source along with additional ones from user input. Then there are two distinct scenarios at play, each requiring its own approach:

Outputting values of source with timings based on intermediate: Utilizing the combineLatest operator can easily achieve this task:

const source_with_timing_from_intermediate : Observable<TSource> = intermediate.combineLatest(source, (i, s) => s);

Comparing the most recent value from intermediate with source: Although it appears similar, using combineLatest may not be reliable because if you perform a simple operation like:

const is_different : Observable<bool> = intermediate.combineLatest(source, (i, s) => i !== s);

If source emits a new value before intermediate catches up, you might mistakenly attribute that previous value to intermediate.

For greater reliability, consider buffering and employing a subject:

// untested
const derived : Observable<TSource> = (function() {
  const source_buffer = new Queue();
  const subj = new Subject();
  source.forEach(s => {
    source_buffer.enqueue(s);
  });
  intermediate.forEach(i => {
    subj.onNext(source_queue.peek() === i);
    if(source_buffer.peek() === i) source_buffer.dequeue();
  });
  Promise.all([
    source.toPromise(),
    intermediate.toPromise()
  ]).then(() => subj.onClose());
  return subj.asObservable();
})();

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

Divide JSON arrays into separate select boxes

I have integrated AngularJS into certain sections of my website, rather than using it for the entire site. Currently, I am dealing with a scenario where I have a pair of select boxes, one dependent on the other. One box contains a list of countries, while ...

Toggling javascript functionality based on media queries

On one of my slides, I want to display images that are specific to different devices like iPhone, iPad, and desktop. I am looking for a way to filter these images based on the device. Using display:none won't work as it's JavaScript, but here is ...

Pressing the button results in no action

I am currently developing a program that randomly selects 5 words from a database and inserts them into an array. Although the page loads correctly initially, nothing happens when the button is clicked. None of the alerts are triggered, suggesting that the ...

What is the best way to eliminate all instances of the period symbol from an array?

How can I eliminate all instances of . from my array? var arr = ['...my name is apple', 'my girl .... friend is banana.......']; Below is the code snippet I am currently using. var arr = ['...my name is apple', 'my g ...

Using Javascript function with ASP.NET MVC ActionLink

I need help with loading a partial view in a modal popup when clicking on action links. Links: @model IEnumerable<string> <ul> @foreach (var item in Model) { <li> @Html.ActionLink(item, "MyAction", null, new ...

Continue looping in Javascript until an empty array is identified

Currently, I am in search of a solution to create a loop in Javascript that continues until the array of objects is empty. The object I am working with looks like this: "chain": { "evolves_to": [{ "evolves_to": [{ ...

Combine rows with the same value in the first column of an HTML table

My HTML table has dynamic content, and I need to merge rows in the first column only if their values are identical. You can see an image of the table here. Specifically, if the values in the first column match, those rows should be merged together while le ...

There seems to be an issue with accessing /puffins/5f298d0ebcbaf254dcf282b3 at

Having trouble with my destroy route - it keeps returning an error. I've spent a lot of time trying to debug it but no luck yet. Can you lend a hand? All other CRUD routes are functioning correctly. //THE ROUTE app.delete('/puffins/:id', (re ...

Retrieve the URL for the React component

I'm facing some challenges with React fundamentals :/ I have a piece of code that creates a table using JSON data: import React from 'react' import { DataTable } from 'react-data-components'; function createTable(data) { ...

Can you create a stroke that is consistently the same width as the container BoxElement?

Utilizing a BoxElement provided by the blessed library, I am showcasing chat history. New sentences are inserted using pushLine. To enhance readability, days are separated by lines (which are added using pushLine). The width of each line matches that of t ...

What steps can be taken to diagnose the cause of a failed Jquery AJAX request?

I am attempting to utilize the Yahoo Finance API to retrieve data in CSV format through Javascript. However, my current implementation shown below is not successful. $.ajax({ type: "GET", url: "http://finance.yahoo.com/d/quotes.csv?s=RHT+MSFT&f=sb2b3j ...

Failed PHP response when jQuery was called

I'm working on a project that involves two files: one PHP and one HTML. The HTML file acts as the user interface where users input their queries, while the PHP file handles the processing and events before returning the output back to the HTML file. I ...

What is the proper usage of a jwt token?

I'm completely new to this and I've dedicated all my time to figuring out how to create a mechanism for generating JWT tokens. These tokens are necessary for identifying the 'signed in' status of users. I opted for FastAPI, and after s ...

The MDX blog was set up to showcase markdown content by simply displaying it without rendering, thanks to the utilization of the MDXProvider from @mdx-js/react within Next JS

I'm currently in the process of setting up a blog using MDX and Next.js, but I've encountered an issue with rendering Markdown content. The blog post seems to only display the markdown content as plain text instead of rendering it properly. If y ...

Trouble with Ajax program loading properly in Chrome browser

I have developed a small ajax program and encountered an issue. While it works perfectly fine on Internet Explorer 11, it does not function correctly on Chrome and Firefox. Here is the HTML file snippet: <html> <head><title>Ajax Page< ...

Tips for activating multiple CSS animations when scrolling

I am currently working on a project that involves multiple CSS animations. However, I am facing an issue where these animations only occur once when the page initially loads. I would like them to trigger every time the user scrolls past them, regardless of ...

The unexpected occurence of the Onbeforeunload exception

I am attempting to create an exception for onbeforeunload and display a warning about potential data loss whenever the quantity is not zero: Here is what I have tried so far: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www. ...

I am interested in incorporating the ability to select and scroll the window without needing to interact with the scroll bar by

Imagine a visitor wanting to highlight all the information on a webpage. They choose to start dragging their cursor towards the bottom of the window. How can we enable the webpage to smoothly scroll down as they do this? ...

When you use map to transform the value, Observable will consistently return as undefined

Can anyone help me figure out why, when I transform the observable, it returns undefined in the console log even though there are assigned values? HTTP Request getLibraryCardPeople(bookName: String): Observable<people[]> { return this.http.get<Li ...

Is it better to include the Google Analytics code in the master page or on every individual page of an asp.net

Looking for a way to track every page on my website effectively. Should I insert the Analytics tracking code in each aspx page inherited from the master page, or is it sufficient to place it only in the master page to track all inherited pages? ...