Is there a way to retrieve the final value from an Observable?

Trying to retrieve the last value from an observable. Here is an example of the code:

// RxJS v6+
import { lastValueFrom, Subject } from 'rxjs';
import { scan } from 'rxjs/operators';

async function main() {
  const subject = new Subject();

  const example = subject.pipe(
    scan((acc, curr) => {
      return Object.assign({}, acc, curr);
    }, {}),
  );
  const subscribe = example.subscribe((val) =>
    console.log('Accumulated object:', val),
  );
  subject.next({ name: 'Joe' });
  subject.next({ age: 30 });
  subject.next({ favoriteLanguage: 'JavaScript' });

  console.log('+++++++++++++');
  const resp = await lastValueFrom(example);
  console.log(resp);
  console.log('end');
}

main()
  .catch(e => {
    console.error(e);
  })
  .finally(async () => {
    console.log('final');
  });

The output displayed is:

➜  npns-service git:(mr/master/658) ✗ ts-node prisma/test.ts
Accumulated object: { name: 'Joe' }
Accumulated object: { name: 'Joe', age: 30 }
Accumulated object: { name: 'Joe', age: 30, favoriteLanguage: 'JavaScript' }
+++++++++++++

I am unable to see the response output message. How can I access the response value from the example Observable?

Answer №1

Revise your code to ensure that your observable is properly completed:

setTimeout(() => { // Using setTimeout to work with JS's event loop
    subject.next({ name: 'Joe' });
    subject.next({ age: 30 });
    subject.next({ favoriteLanguage: 'JavaScript' });
    subject.complete(); // Indicates the completion of our observable emission
    // Any subsequent subject.next(something) calls here would be ineffective as the observable is complete 
}, 0);

console.log('+++++++++++++');
const resp = await lastValueFrom(example);
console.log(resp);
console.log('end');


Failure to complete an observable leaves the possibility of it emitting further values unpredictably in the future. It is vital to establish a condition for completion.

Sidenote: Placing the emission code within the event loop allows for proper await functionality in the subsequent code. Otherwise, the subject may complete synchronously before the following code is executed.

Update 1: How can I retrieve the latest value from an observable?

Create example as an observable that retains (buffers) the most recent emission. Simply utilize take(1) to access the buffered value.

const subject = new Subject();

const example = subject.pipe(
    scan((acc, curr) => Object.assign({}, acc, curr), {}),
    shareReplay(1)
);
example.subscribe(val =>
    console.log('Accumulated object:', val)
);

subject.next({ name: 'Joe' });
subject.next({ age: 30 });
subject.next({ favoriteLanguage: 'JavaScript' });

console.log('+++++++++++++');
const resp = await lastValueFrom(example.pipe(take(1));
console.log(resp);
console.log('end');

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

Key steps for effectively implementing a Substring-Filter on a JSON array in d3

Trying to apply filtering on a JSON data array structured like this: var data = [ { "key": "FirstGroup", "color": "#1f77b4", "values": [ { "label ...

Display the text from a function in an imported component using React

Attempting to break down HTML chunks into smaller pieces stored in the components folder. (Note: the HTML is actually written in JSX). The goal is to import the [Navigation] component and have it display its content. I am aware that there are tools avail ...

JavaScript tip: Finding the total sum of strings with time format (e.g. 00:00:00)

I have an array that contains time values: // hours, minutes, seconds let arr = ["00:00:30", "00:20:00", "01:00:10", "05:10:15"] Is there a way to calculate the total sum of these elements? output: "06:30:55" ...

Troubleshooting problem with MongoDB queries within a for loop

I have an array of user emails obtained from the post data. My goal is to find the _id associated with each email. Here's the for loop I attempted: var studentIds = []; for (var i = studentEmails.length - 1; i >= 0; i--) { var email = studentEm ...

Angular: Autocomplete field automatically shifts focus when an item is removed

I am currently working on an Angular 2 application that utilizes PrimeNG components. One of the UI features includes an autocomplete component with multi-select functionality (p-autoComplete) similar to the one showcased in the official documentation: < ...

What could be causing my React component to only render after pressing ctrl + shift + R?

I am facing an issue with my chrome extension where it only appears after refreshing the page using ctrl + shift + r. However, there is a new problem that arises when I click on a link that refreshes the page, causing the extension to disappear and requiri ...

Printing in HTML is limited to only one page

While printing an HTML table that can vary in length, I often encounter the issue of it printing multiple pages. Is there a way to limit the printing to just one page through coding? Yes, you can achieve this by using the option in the browser print dialog ...

Capture a screenshot of an embedded object and include it in an email using the mailto function

Is there a way to capture a screenshot of a flash object on a webpage and then send it via email using a mailto: form submission to a designated address? I have attempted to use different JavaScript techniques, but none seem to be successful. Appreciate a ...

Use the filter method to organize arrays into subarrays based on their length, filtering out those with a length greater than or

Hey there, I've been working on incorporating the array filter property to separate subarrays that are greater than and less than 3 into two distinct functions. Unfortunately, I'm a bit stuck on how to continue fixing my functions. Can someone pr ...

Top method for showcasing animated images (HTML/CSS/JS)

For my website, I want to create an engaging animation showing a coin being flipped multiple times in the air before landing on a specific side. After the animation finishes, I would like it to transform into a static image of the final result. I've ...

What is the process for connecting a form to a model in Angular 6 using reactive forms?

In the time before angular 6, my approach involved utilizing [(ngModel)] to establish a direct binding between my form field and the model. However, this method is now considered deprecated (unusable with reactive forms) and I find myself at a loss on how ...

What are the reasons behind the inability to import an image file in Next.js?

Having an issue with importing image file in Next.js I'm not sure why I can't import the image file... The image file is located at 'image/images.jpg' In Chrome browser, there are no error messages related to the image, However, in ...

Issue with Chrome not triggering onMouseEnter event when an element blocking the cursor disappears in React

Important Note: This issue seems to be specific to Chrome Currently, React does not trigger the onMouseEnter event when a blocking element disappears. This behavior is different from standard JavaScript events and even delegated events. Below is a simpli ...

Is it possible for me to retrieve data in object using double v-for?

I am attempting to create a dynamic table using the following objects: <tr v-for="product in allPosts" :key="product.id"> <td v-for='(item, i) in checked' :key='`item${i}`'>{{product.item}}</td> </tr> In th ...

Having difficulty accessing `props` in a React JS and Next JS application

Currently, I am developing a React application that utilizes Server Side Rendering. In this project, I am using React Js and Next Js as my primary framework. My goal is to retrieve initial props using the getServerSideProps method by consulting the documen ...

The component cannot be created using shallowMount because vm.$refs['VTU_COMPONENT'] is not defined

Not sure if it's a bug or if I'm making a mistake. I attempted to use shallowMount to mount my main App component, but it doesn't seem to work. The error message I receive is: Cannot set properties of undefined (setting 'hasOwnProper ...

Interoperability between AngularDart and AngularJS

Discovering the Dart language and AngularDart after working with AngularJS has been exciting. However, my biggest concern is whether AngularDart supports all the amazing modules that AngularJS offers. I haven't been able to find any information on whe ...

Is there a way to ensure that @angular/core is utilizing the most up-to-date version of zone.js in its peerDependencies configuration?

This code passes the test, but there is an issue: it('should successfully retrieve data when getDownloadProgress() is called', (done: DoneFn) => { let response = { 'process': {}, 'success': 'success ...

HTML dropdown menu to trigger an action with the submitted URL

I need assistance creating a menu of options with corresponding URL actions. Here is the structure I have in mind: <form> <select> <option value="1">1</option> <option value="2">2</option> <option value="3 ...

Unlocking the invitable_friends permission dialog on Facebook API: A step-by-step guide

During the installation process of an app, users are given the choice to revoke the invitable_friends permission. If this happens, I would like to request the invitable_friends permission again. Some apps seem to be able to open a dialog requesting this pe ...