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

Encounter an issue during npm installation of electron: "Error verifying the initial certificate."

I recently developed a new app directory and ran the command npm init. However, I encountered an issue while trying to install Electron with the following line of code: npm install electron --save-dev. The error message I received is as follows: > [em ...

Declare, condition, and output all in a single statement

Is there a method to condense the content inside the function below into a single line? I want to avoid declaring check. function Example { const check = this.readByUuidCheck(props) if (check) return this.readByUuid(check) } I am seeking ways to ...

Running JavaScript within Electron is a straightforward process

Looking to create an Electron application that can take code entered into a text area, execute it, and display the result. Any advice on converting the text to JavaScript and running it? ...

Tips on dynamically looping the formcontrolname and implementing validation strategies

Looking for a way to validate multiple looping of dynamic formControlName="xxx" in select field. Check out my HTML code: <ul *ngFor="let detaillist of stressli.stresstabdetails;"> <li> <div class="form-container"> ...

css: positioning images with overlap in a responsive layout

Two divs have been created with background images, both displaying the same image but in different colors - one grey and the other green. These images are waveforms. Initially, only the grey image (div1) is visible while the green image (div2) remains hid ...

React error: Unable to iterate through items because property 'forEach' is undefined

I am trying to implement private routing validation using the following code: import React from 'react'; import { Route, Redirect } from 'react-router-dom'; import routes from '../../routing/routes'; export default function ...

Working with high-resolution images on HTML5 canvas

I am faced with a challenge of incorporating a 15000x15000 px vector image as the backdrop for my canvas project. It is essential to crop specific sections of this image swiftly and consistently, especially within requestAnimationFrame. My current method ...

Guide on activating an event when a slider image is updated using jquery

I am working on a project that includes a slider. I have been trying to trigger an event when the slider image changes, but so far using the classChange Event has not been successful. Here is the link to my code: [1] https://codepen.io/anon/pen/gzLYaO ...

Having trouble sending form data using the jQuery AJAX POST method?

I am facing an issue with a simple form that is supposed to send data to PHP via AJAX. However, when I submit the form, the data does not get sent across. Here is the JavaScript code: $(document).ready(function(e) { $('#update').submit(func ...

Transmitting data from Angular to .NET Core for seamless integration

I have been attempting to send an xls or any other file from my angular application to a .NET core controller, but none of my methods seem to work... Below is my component where I call my service upon button click: handleFileInput(file: FileList) { this. ...

Issues with Vue enter transitions not functioning as expected

I am currently involved in a project where I need to implement enter and exit animations for some components. When a component enters the screen, it should come from the bottom, and when it leaves, it should go upwards. The intended functionality is that w ...

Is there a jQuery or Javascript alternative to CSS Counter?

Can a counter be implemented that changes the text of a tag directly using jQuery/Javascript? For example, if there were two tags like this: <a>hello</a> <a>bye</a> After executing the jQuery/JS function, the result would be: < ...

Obtain the alternative attribute value from the adjacent element and save it to a variable using jQuery

I'm a beginner with jquery and am trying my hand at creating a simple drag and drop game using the following HTML structure: <div class="set-text"> <div class="text">cinema</div> <div class="text">post-office</div> ...

Having trouble with the Vuejs validation code not functioning correctly?

I need help with a JavaScript function that posts objects to the backend only if all items are numbers. Here is the code snippet I'm working with: var MyApp = new Vue({ el: '#my_element', data: { errors: [], ...

What is the best way to position an image alongside text using Vue and Buefy?

I'm looking to add an image next to my text in Vue using Buefy. Take a look at the code I have so far, can someone offer some guidance? <template> <section class="hero is-link is-fullheight-with-navbar"> <div cla ...

What is the best way to check for a matching array value in my menu list and apply a corresponding class tag to it?

I need a way to dynamically add a class to tags that match specific array values. My menu list consists of 150 items, and I want to add a class to the tag whose text matches an element in the array. <ul class="nav main" id="tabs"&g ...

Tips for concealing an entire row of a table with Jquery

I am currently working on a system that involves a table with anchor tags named original and copy in each row. By clicking on these anchor tags, we are able to update the database whether the item is an original or a copy using ajax. However, I am facing a ...

The dropdown in vue-multiselect automatically closes after the first selection is made, ensuring a smooth user experience. However,

I am experiencing an issue where the dropdown closes after the first selection, despite setting close-on-select="false". However, it works properly after the initial select. You can observe this behavior directly on the homepage at the following link: vue ...

What is the reason behind TypeScript requiring me to initialize a property even though I am retrieving its value from a local reference?

I am just beginning to explore Angular. This is the template for my custom component: <div class="row"> <div class="col-xs-12"> <form action=""> <div class="ro"> <d ...

Combining Multiple .ts Files into a Single File: A Simplified Application Structure with TypeScript 1.8

Currently, I am in the process of developing an Electron application and I have decided to implement TypeScript for this project. While TypeScript essentially boils down to JavaScript in the end, my familiarity with it makes the transition seamless. As of ...