How to access the values before and after each emission in RxJS

Looking to find the variance in emissions from a single Observable.

Is it possible to access both the current and previous emission of an Observable when it emits a new value? I'm envisioning something like this:

ob$.subscribe(val => {
  console.log(val)
  // First emission: [1,2,3]

  // Second emission: [1,2,3,4]

  console.log(findDifference(before, after)) // [4]
})

How can this be achieved? Do I have to keep track of each emission in a higher-level variable or is there a clever RxJS method for accomplishing this?

Answer №1

Utilize the scan operator in order to compare the previous value

   const computeArrayDifference = (initial, final) => {
    // Complete the function implementation here
    
    const diff = .........
    return diff
    }
    
    
    observable$.pipe(scan((initial,final) => computeArrayDifference(initial,final), [])).subscribe(result =>  console.log(result))

This approach is effective

Answer №2

If you want to achieve this, utilize the bufferCount operator, known for its high modularity:

bufferCount(2, 1)

This will generate a fresh buffer with a size of 2 following every 1 emission from the source.

Alternatively, there is also the pairwise() operator that carries out the same function precisely.

Answer №3

To achieve the desired result, I would employ the use of startWith in conjunction with pairwise()

 const customObservable = of('stringFromObservable')
  .pipe(startWith('defaultString'), pairwise())
  .subscribe(stringArray => console.log(stringArray[0], stringArray[1]));

This piece of code will output: 'defaultString', 'stringFromObservable'.

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

Error: Unable to initialize i18next as a function

For my current project, I am utilizing TypeScript and i18next for internalization. TypeScript version: 2.1.4 i18next version: 2.3.4 @types/i18next version: 2.3.35 In the specific file: import * as i18next from 'i18next'; i18next.init({ ...

What is preventing me from manipulating this Object outside of the ngOnInit() function?

I've been working on a project that involves fetching data from the server and manipulating it within the .ts file. However, I seem to be facing a common issue related to Typescript/angular concepts that I'm struggling to grasp...I would really a ...

Best practice for incorporating the cq-prolyfill third-party JavaScript library into an Angular 5 application

I'm experiencing an issue with the cq-prolyfill library not functioning properly when included through a typescript import statement within an angular module. I have confirmed that it is included in my vendor bundle, but for some reason the initial se ...

Exploring the Relationship Between the ngOnInit and ionViewWillLoad Lifecycle Hooks

After a few months of utilizing Ionic Framework (ionic-angular 3.9.2 latest) for developing Progressive Web Apps, I find myself pondering the distinction between ngOnInit and ionViewWillLoad. If my understanding serves me right, ngOnInit is an Angular lif ...

How can I conditionally make an object property optional in TypeScript depending on another type?

To better illustrate my situation, I believe presenting it in code would be most effective: interface IPluginSpec { name: string; state?: any; } interface IPluginOpts<PluginSpec extends IPluginSpec> { name: PluginSpec['name']; // H ...

Sorting by Date in JavaScript

My goal is to filter out the elements in an array that have a date (converted from string) greater than a specific date. _this.downloadData.forEach(_d => _d.LogTime = _d.LogTime.toString()); console.log(_this.downloadData.filter(x=>new Date(x.LogTi ...

Leveraging mongoose populate in a Node.js environment with TypeScript

I am struggling to solve this issue. I am currently working on a node express mongoose server with code written in TypeScript and encountering the following error: Property 'populate' does not exist on type 'Document | Aggregate | Model | ...

A method to extract a specific JSON key value from a nested JSON structure in Angular using a given parameter

I am completely new to Angular and have a json file that contains different families. I need to retrieve the value associated with a specific family based on user input. For example, if the user inputs 'ciena', I should be able to return the json ...

.NET Core backend experiences file becoming null during Angular multipart upload

I am having some issues while attempting to upload a basic file to my backend dotnet core application. The problem is that the file ends up being null, whereas the description is not. This is my .NET Core controller: [AllowAnonymous] [HttpPost] [Route("u ...

When working with a union type in TypeScript, it is important to note that the property may

Imagine a scenario where I am dealing with two specific interfaces: interface Box { x: number y: number } and interface ColouredBox { x: number y: number colour: string } For the sake of this discussion, let's assume that the ...

Tips for retrieving a date and time selection from a mat-date-picker and mat select?

I am currently utilizing Angular calendar to display various events. Each event is defined by the following parameters: event:{ title: string, start: Date, end: Date }; As material design does not offer a date-time picker, I have opted for usi ...

Tips for relocating the indicators of a react-material-ui-carousel

I am working with a carousel and dots indicators, but I want to move the indicators from the bottom to the circular position as shown in the image below. I attempted using a negative margin-top, but the indicators ended up being hidden. Is there another ...

Creating an auth guard in Angular Fire v7 using the latest API (not backwards compatible)

I encountered an issue Error: Unable to handle unknown Observable type when attempting to utilize v7 Angular Fire with the latest API. Specifically "@angular/fire": "^7.4.1" which corresponds to angular 14, firebase 9. Please not ...

Leveraging ZOD's discriminatedUnion() method to differentiate among three different forms

ValidationSchema = z.object({ AuthenticationBlock: z.object({ ChoiceOfForm: z.enum() DataBlock: z.discriminatedUnion(ChoiceOfForm, [ z.object({ ChoiceOfForm = 1, empty fields}) //corresponds to the basic form z.object({ ChoiceOfForm = 2, just ...

How can you create the "Property within Key of Type" structure using Zod?

My current challenge involves a Zod shape with multiple keys. I am in need of creating another shape that mirrors the same keys, but with different types. In regular Typescript, this could be achieved with: type TypeA = { something1: number something2: ...

What is the method for determining the data type of a key within an interface?

How do I retrieve the data type of User.name? interface User { id: number; name: string; } I am looking to specify my other type as follows. type UserInstance { name: <infer type "string" from User interface>; ... } The goal is to ...

Next.js Version 13 - Unable to find solution for 'supports-color' conflict

Currently in the midst of developing a Next.js 13 app (with TypeScript) and utilizing the Sendgrid npm package. An ongoing issue keeps popping up: Module not found: Can't resolve 'supports-color' in '.../node_modules/debug/src' ...

International replacement of external interface exportation

Currently, I am utilizing the @react-native-firebase/messaging library and invoking the method messaging().onNotificationOpenedApp(remoteMessage => ....) I am aiming to replace the property data within the type of remoteMessage in order to benefit from ...

What causes the frustratingly slow transition between two components on Android?

I am currently in the process of developing a compact puzzle app that resembles a crossword using Expo, React Native, and Typescript. Below is a concise version of the PuzzleMain component: const PuzzleMain: React.FC<PuzzleMainProps> = ({ navigation ...

Getting the value of a CSS Variable from Radix UI Colors with Javascript/Typescript: A step-by-step guide

Currently, I am attempting to dynamically retrieve the Radix Colors values in JavaScript. The reason for this requirement is that I generate these colors based on user input, resulting in values that are variable. As a result, I cannot hardcode the values. ...