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

The communication between the extension and chrome.runtime.connect() fails, possibly due to an issue with the chrome manifest version

I've been working on converting a Chrome extension that stopped functioning in manifest version 2. I've removed inline JavaScript and switched from chrome.extension.connect to chrome.runtime.connect. However, I'm still encountering issues wi ...

emptyQueue in jQuery

I'm currently working with a jQuery script that takes the src of an image, places it in a hidden div, and enlarges the image with an animation when hovering over the requested image. However, I've encountered an issue where the clearQueue or stop ...

Choosing the image that represents your website in Safari web previews

Every time I check iCloud.com on my Safari top sites, the thumbnail is always the same. I'm curious about how I can automate this for my own website. ...

Remove rows that have values within a specific range

I'm facing an issue in Google Sheets where I'm attempting to delete entire rows on the "Data" sheet if any value in column B matches values from the range D3:E20 in the "Backend" sheet. The code provided works when a word is hardcoded as the cond ...

The use of the cache-control request header field is prohibited when attempting to sign in with an Angular frontend during the

I recently developed an application using Angular with a Java backend in Spring. However, I'm facing an error when trying to log in and it's related to CORS policy. Whenever I try to login, I receive the following error message: Access to XMLH ...

Tips for navigating through a webpage by scrolling

My goal is to automatically scroll down to the bottom of the page and then perform a specific action. With the help of uiautomator, I was able to retrieve the following information: index=2, resource-id=com.manoramaonline.arogyam:id/pager,class=android.sup ...

The Discord bot seems to be stuck in time, relentlessly displaying the same start time without any updates in between. (Built with Node.js and Javascript

const Discord = require('discord.js'); const client = new Discord.Client(); var moment = require('moment'); const token = '//not telling you this'; const PREFIX = '!'; client.on('ready', () =>{ con ...

Error message: Unable to access .exe file through HTML link

We have a need to include an HTML link on our intranet site that, when clicked, will open an .exe file that is already installed on all user machines. I attempted the following code: <a href = "C:\Program Files\Cisco Systems\VPN&bsol ...

Fixing the issue of scrollbars not working in existing divs while creating new jscrollpane divs in jQuery

Utilizing the jquery.uploadfile.min.js plugin to upload multiple files results in creating a div of jscrollpane class each time a file is uploaded. However, there seems to be an issue where only the scrollbars in the last created div are functioning proper ...

The Express GET route does not support parameters or additional paths

I am facing an issue with making a fetch request when trying to add additional path or parameters... Here is what I want to achieve: const fetchOwnerCardList = () => { fetch("http://localhost:5000/api/card/ownerCards", { method: "GET", header ...

Ways to conceal a dynamically generated div upon page load?

I am currently facing a scenario where I need to dynamically create a div. My initial approach was to create it on the document ready event, but the requirement is for it to be displayed only upon selection. The problem I am encountering is that the empty ...

How can I dynamically insert a variable string into a link tag using React and TypeScript?

I am just starting out with javascript and typescript, and I need to generate a link based on certain variables. I am currently facing an issue trying to insert that link into <a href="Some Link"> Some Text </a> Both the "Some Text" and "Som ...

Having trouble getting npm install to add any libraries? Wondering how to fix this issue?

Currently, I am using Node version 14.15.5, npm version 6.14.11, and working on VS Code. I attempted to install two packages with the following commands: npm install express npm install lodash Unfortunately, neither installation was successful. This ...

Utilizing Javascript to share images from a public Facebook page to a user's timeline via the Facebook API

Can someone assist me with finding a way to share a photo from a public Facebook page to the user's timeline using JavaScript? Is it possible to achieve this with FB.api or FB.ui? I have successfully shared feeds to the timeline using FB.ui, but am no ...

The Angular model finally refreshes its values after a console.log() is executed

UPDATE After further investigation, I discovered that the issue was not related to Angular itself, but rather a mistake in the update function within the node server controller. I have provided the fix below for reference, and decided to keep this questio ...

What is the process for searching my database and retrieving all user records?

I've been working on testing an API that is supposed to return all user documents from my Mongo DB. However, I keep running into the issue of receiving an empty result every time I test it. I've been struggling to pinpoint where exactly in my cod ...

The datetimepicker is not functioning properly

I'm experiencing an issue with the datetimepicker where it doesn't display a calendar when I click the icon. Interestingly, the Chrome browser isn't showing any errors in the development console. <script src="Scripts/jquery-2.1.1.min.js ...

The Java Selenium script encountered an illegal type error when trying to execute JavaScript through JavaScriptExecutor: driverFactory.CustomWebElement

I have a CustomWebDriver class that extends the functionality of JavascriptExecutor. Here is my implementation: @Override public Object executeScript(String script, Object... args) { return ((JavascriptExecutor) driver).executeScript(script, args); } ...

Insert DOM elements at the start of the parent element

I'm currently using the following JavaScript code to insert AJAX responses into a div with an ID of results: document.getElementById("results").innerHTML=xmlhttp.responseText; The issue I am encountering is that this code adds all new elements after ...

No user was located using Mongoose.findOne()

Utilizing fetch() to make a call to a URL looks like this: const context = useContext(AuthContext); const navigate = useNavigate(); const handleSubmit = (event) => { event.preventDefault(); const dat ...