Rxjs: accessing the most recent value emitted by an observable

As shown in the demo and indicated by the title

const { combineLatest, interval, of } = rxjs;
const { first, last, sample, take, withLatestFrom } = rxjs.operators;

const numbers = interval(1000);

const takeFourNumbers = numbers.pipe(take(4));
takeFourNumbers.subscribe(x => console.log('Next: ', x));
setTimeout(()=>{
 console.log('how can we get the latest value which is 1?');
 takeFourNumbers.pipe(first()).subscribe(v=>console.log(v,'actual get'))
},2500)
// Logs:
// Next: 0
// Next: 1
// how can we get the latest value which is 1?
// Next: 2
// 0 actual get
// Next: 3
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9fede7f5ecdfa8b1aab1aa">[email protected]</a>/dist/bundles/rxjs.umd.js"></script>

In my scenario, I specifically aim to retrieve the most recent value for a one-time task. How can this be achieved?

I have contemplated about the possibility of an operator such as takeLatest() or latest(), but haven't come across any.

Answer №1

The core issue here lies in the need to share a provider (data source) or decide between "Hot vs Cold" observables. The desired outcome is to have the most recent value shared among different subscriptions, indicating a preference for a hot observable. The Observable generated by the interval operator is cold by default, requiring it to be converted into a hot observable. This transformation can be achieved with the following code snippet:

const takeFourNumbers = numbers.pipe(take(4), shareReplay(1));

Subsequently, regardless of the number of times you subscribe to it, all subscribers will access and share the same value.

On a side note, it's important to use shareReplay to ensure that the last emitted value is immediately available upon subscription. Therefore, when subscribing within a setTimeout function, you should receive 1 as expected.

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

Retrieve data from Firestore using React and log it outside of the asynchronous function

Seeking a way to retrieve data from userRef and use it to initiate another asynchronous call to another document (e.g. bikes) in order to display that bikes doc on the page Currently, the userDetailslog in the Home screen function prints {"_U": ...

Retrieve an individual item from the observable array

How can I create a function that takes an Observable<T[]> and returns Observable<T>? Here is the scenario: I have two methods: getTransactions(): Observable<Transaction[]>{ ... } getTransaction(id: number): Observable<Tra ...

Make sure to wait for the fetch response before proceeding with the for loop in JavaScript using Node.js

I am facing an issue with my function that connects to a SOAP web service. The problem arises from the fact that the web service has limited connections available. When I use a for or foreach loop to search through an array of items in the web service, aro ...

Retrieve a static property from a specific type

I've encountered a dilemma with the code snippet below: class Action { public static DEPENDENCIES: (typeof Action)[] = []; public static MIN_USES: number | null = null; public static MAX_USES: number | null = null; } class SomeAction ext ...

Scaling divs proportionately using a container

I have numerous elements enclosed within a <div class="wrapper">. My aim is to resize this outer div and ensure that the inner elements scale proportionately along with it. For instance, when dealing with a group of SVGs, adjusting the transform pro ...

React fails to recognize the key prop

When creating a list of TSX elements, I utilized the following code: this.productsModel = this.state.products.map(o => ( <Grid.Column key> However, I encountered a warning from React: Warning: Each child in a list should have ...

Is there a way to use jQuery to automatically make a field stand out visually?

I am looking for a way to make a text field automatically underline as the user types. The line should follow along with the characters in real-time, and when the user moves away from the field, I want the line to fill up the entire width. This signifies t ...

Hide the menu when a menu link is selected

After conducting extensive research, I have come across several scripts that can achieve what I am trying to do. However, I am unsure of how to implement them with my particular WordPress theme. Therefore, I am seeking assistance here: The theme I am usin ...

Angular Service Fails to Execute Upon Initial Loading

In my current project, I am utilizing Angular 9.0.7 with a Node.js (Express) backend and an Angular frontend. The issue I'm facing is that the service function responsible for fetching data from the backend is not being invoked on the initial page lo ...

I can't understand why this question continues to linger, I just want to remove it

Is there a valid reason for this question to persist? I'm considering removing it. ...

Ways to resolve the error 'Node Sass unable to locate a binding in your current environment' while executing npm run build

When executing sudo npm run build, I encountered an error stating that it cannot find the binding for sass. My npm version is currently 11.13.0 and I have only one version installed. I have tried various solutions such as npm install node-sass, npm rebui ...

Alter the default time zone in JavaScript

PHP features a function known as date_default_timezone_set which impacts the GMT time that is used by the Date() command. Is there a way for this function to also impact JavaScript? Here is a custom function I have: function calcTime(offset) { d = n ...

Struggling with passing parameters through a route and displaying them in the Reddit app using React?

I'm currently working on a project that involves displaying threads from various subreddits when a user clicks on a list item using routes and react. However, I've encountered some issues with getting the information to display correctly. Below i ...

Creating a custom function that targets a specific element

When working with JavaScript, you may often encounter functions written in the form of document.getElementById("element").someFunction(); or $("element").someFunction(); rather than the traditional someFunction($("element"));. This is similar to a function ...

error when trying to bind attributes to knockout components

I am trying to dynamically add an id attribute to a tag, but it keeps giving me an error. "Uncaught ReferenceError: Unable to process binding "attr: function (){return {id:id} }" Message: id is not defined" Here is my HTML code- <label data-bind= ...

"Utilize ngclass to set CSS classes based on enum string values

Is there a way to directly call an element in Angular when using an enum to organize component styles? Instead of writing multiple ng class expressions or dynamically passing them to the element call. button-types.ts export enum ButtonTypes { Primary ...

Having trouble uploading a PNG image (logo) with Cypress

I have been attempting to upload a png file using Cypress and here is what I have tried so far: Cypress.Commands.add('upload_image', (fileName, selector) => { return cy.get(selector).then(subject => { return cy.fixture(fileName, &apo ...

What is the method in AngularJS2 for using TypeScript to inject dependencies into components?

I have been encountering different methods of injecting dependencies into my component and not all of them seem to be working for me. I am curious about the advantages and disadvantages, what the recommended best practices are, and why some methods are not ...

Limiting the displayed portion of a table and implementing scrolling instead

I am currently working with a static HTML template that contains the following code: <table> <thead></thead> <tbody></tbody> </table> Using jQuery and AJAX, I am dynamically adding and removing rows and columns ...

Fetching a substantial amount of data via AJAX to generate a graph

Currently, I am in the process of developing a server that will supply data and information to both a web client and a mobile client in the second phase. One of the key features is displaying this data on a graph, such as showing the price of a stock over ...