Retrieve the final variable in an Observable sequence

In my code, I have a variable called 'messages' which stores messages from a conversation:

messages: Observable<Message[]>;

To populate the 'messages' variable, I do the following:

const newMessage = new Message(objMessage);
newThread.messages = Observable.of([newMessage]);

I want to automatically update my 'lastMessage' variable to always hold the latest message in the 'messages' variable:

lastMessage: Message = null;

Here is what I attempted, but it's not working as expected:

const messagesThread: Thread = threads[message.thread.id];
      if (!messagesThread.lastMessage ||
        messagesThread.lastMessage.date < message.date) {
        messagesThread.lastMessage = message;
      }

//////////////////////////////////////////////////////EDIT/////////////////////////////////////////////////////////

This is the function responsible for adding a new message:

addNewMessage(objMessage: any) : void {
    const flo: User = new User(objMessage.author, objMessage.site);
    const newThread: Thread = new Thread(objMessage.id, [flo]);
    const newMessage = new Message(objMessage);

    objMessage.date = moment().toDate();

    newThread.messages = Observable.of([newMessage]);
    newThread.messages.last().subscribe((message) => {
      newThread.lastMessage = message;
    });                    //DOESN'T WORK

    objMessage.thread = newThread;

    this.addMessage(newMessage);
    this.addThread(newThread);
 }

The initializations of my variables are done like so:

messages: Observable<Message[]>;
lastMessage: Message = null;

An error that I encounter is:

Type 'Message[]' is not assignable to type 'Message'

Answer №1

You can utilize the .last(); operator to achieve this

Here's an example from a reliable source

var source = Rx.Observable.range(0, 10).last();

var subscription = source.subscribe(
  function (x) {
    console.log('Next: %s', x);
  },
  function (err) {
    console.log('Error: %s', err);
  },
  function () {
    console.log('Completed');
  });

// => Next: 9
// => Completed

Similarly, you can do it like this:

 newThread.messages.last().subscribe((message)=>{

         console.log('last messages',messages);
   newThread.lastMessage = messages /// NOT that this is messages as an array
 });

NOTE :

Your data stream contains an Observable of messages, hence each event will return a message array, not just a single message

If this isn't your intention, you may need to remove the array structure. It would be beneficial to clarify your objective here

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

Filtering relations in TypeORM can be achieved by using various query criteria

Hello, I have a couple of questions regarding TypeORM in TypeScript. Using Find() Only: I have two tables in my database - Users and Sessions. I am interested in retrieving a specific User along with all their Sessions where the sessions_deleted_at column ...

Switching from HttpModule to HttpClientModule

Angular's transition from HttpModule to HttpClientModule is causing some confusion, as discussed in detail here. The official Angular tutorial at https://angular.io/tutorial/toh-pt6 still uses HttpModule, while the Fundamentals documentation at https ...

Tips for applying unique scss classes to a div based on a specific condition

Currently, I am developing a chat application where I want to showcase messages from one specific user on the right side of the screen while displaying messages from other users on the left side. <ion-item *ngFor="let message of messages | slice:0: ...

Troubles encountered while trying to make MediaRecorder function in Angular 9

Recently, I've been working on integrating Media Recorder into my Angular 9 application by following the instructions provided at this link. However, I have encountered some issues along the way. When I access the page with the Media Recorder compone ...

Best location for Angular PWA update handler?

Running a PWA app led me to think about decluttering the application.component. To achieve this, I created a dedicated service to monitor PWA updates and alert the user: import { Injectable } from '@angular/core'; import { MatSnackBar } from &qu ...

Is it possible to compile using Angular sources while in Ivy's partial compilation mode?

Error: NG3001 Unsupported private class ObjectsComponent. The class is visible to consumers via MasterLibraryLibModule -> ObjectsComponent, but is not exported from the top-level library entrypoint. 11 export class ObjectsComponent implements OnInit { ...

becoming a member of cdk scroll strategy notifications

In the process of creating a unique service that generates cdk overlays, I am faced with the challenge of listening to cdk scroll strategy events. Specifically, I am interested in detecting when the cdk closes an overlay using the "close" scroll strategy. ...

Angular 5 error handler does not support service calls

My HTTP calls are placed inside a service, as they should be. Within that service, I inject another service for handling error notifications. In an interesting turn of events, I noticed that when I place the notification call inside the catchError pipe, e ...

The angular2-markdown module encounters errors

I am currently working on implementing a markdown editor in a form within my Angular2 project. To achieve this, I have installed the angular2-markdown module. However, I encountered an error when trying to use it, specifically: "marked" is not a function. ...

When using NextJS <Link, mobile users may need to tap twice to navigate

Whenever I use the NextJS <Link tag on my mobile device, I notice that I have to double-tap for the link to actually route to the desired page. Take a look at the code snippet below: <Link href="/methodology" passHref={true} ...

The minimum and maximum validation functions are triggered when I am not utilizing array controls, but they do not seem to work when I use array controls

Take a look at the stack blitz example where min and max validation is triggered: https://stackblitz.com/edit/angular-mat-form-field-icrmfw However, in the following stack blitz with an array of the same controls, the validation does not seem to be worki ...

Exploring the capabilities of Angular 2.0.0 by testing a component integrated with a

Here's a code snippet of a component in Angular: import {Component, OnInit} from '@angular/core'; import {Route, Router} from '@angular/router'; @Component({ selector: 'app-index', templateUrl: './index.compone ...

Express Server Providers for Angular 17's Server-Side Rendering

I attempted to share my request and response object with the Angular application by defining Providers in the "server.ts" file. However, when injecting them into app.component, they always appear undefined regardless of whether I am in the server or clie ...

extract keys and values from an array of objects

I would like assistance with removing any objects where the inspectionScheduleQuestionId is null using JS. How can we achieve this? Thank you. #data const data = [ { "id": 0, "inspectionScheduleQuestionId": 1, ...

Using NgRx to observe state changes in a service instead of relying on an Effect

Is it possible for a service to monitor state changes and make HTTP calls based on the state value without being triggered by an effect (NgRx)? In other words, can a service react to a portion of the store and eliminate the need for an effect to be involve ...

Understanding the concept of mutable properties in Typescript

Why can the property 'name' in the class 'PersonImpl' be reassigned even though it is not declared as read-only in the Person interface? interface Person { readonly name: string; } interface Greeting extends Person { greet( ...

Discover the solution for seamless integration of TypeScript with the novel `exports` and `main` field

I am currently utilizing Node.js version 16.10.0 along with TypeScript 4.5.5. As part of my development process, I am in the midst of publishing a library and have implemented the following configuration: "main": "./dist/index.js", ...

Angular 4 async pipe not functioning as expected for Observable to update UI

I have a simple dataset loaded into an observable as shown below: public tasks: Observable<UserTask[]>; constructor(private dataService: HttpdataService, private changeDetector: ChangeDetectorRef) { } ngOnInit() { this.loadTasks(); } loadTasks() ...

How can I prevent right-clicking with Ctrl+LeftMouseClick in Firefox on MacOS?

I'm looking to implement a shortcut using Ctrl+LeftMouseClick in my React project. It functions perfectly on Chrome on my Mac, but in Firefox the shortcut initiates a right mouse click (event.button = 2). I believe this may be due to MacOS's Rig ...

Testing the value of an input in Angular using unit tests

Currently, I am delving into the official documentation of Angular2 which focuses on unit testing (https://angular.io/docs/ts/latest/guide/testing.html). My struggle lies in setting a component's input field value so that it reflects in the component ...