The integration of reduce and scan with a specific focus

RxJS version: 5.5.2

Working with an array const v = [1, 2, 3];

The goal is to convert this array into a Subject initially acting like an Observable until all values (1, 2, 3) are consumed. After that, it should behave like a Subject.

The challenge lies in using reduce on the initial values of v = [1, 2, 3], and then switching to scan each time a new value is added by the Subject.

Current code snippet:

const v = [1, 2, 3];
const sub = new Subject<number>();
const observable = sub.pipe(
  startWith(0),
  concatMap(x => from(v)),
  scan((a, b) => {
    return a + b;
  }, 0),
);
observable.subscribe(x => console.log(x));

When using scan, the following sequence is printed to the console:

1
3
6

The desired output is just the last value 6. Substituting scan with reduce achieves this, but only if the subject is completed (making it unable to receive future values).

To address this, the objective is to print 10 when a new value is sent by the subject through sub.next(4);, and so forth.

Answer №1

To exclude the initial N emissions from scan, you can make use of the skipWhile() operator:

import { Subject } from 'rxjs/Subject';
import { from } from 'rxjs/observable/from';
import { of } from 'rxjs/observable/of';
import { merge, concatMap, scan, skipWhile, tap } from 'rxjs/operators';

const values = [4, 5, 6];
let toSkip;

const sub = new Subject<number>();

const observable = of(values).pipe(
  tap(arr => toSkip = arr.length),
  concatMap(arr => from(arr)),
  merge(sub),
  scan((a, b) => {
    return a + b;
  }, 0),
  skipWhile(() => --toSkip > 0),
);

observable.subscribe(x => console.log(x));

sub.next(3);

The output will be:

9
12

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 behavior in Angular where updates to arrays in child components do not reflect the data passed from the parent is known as "

My child component is not listening for changes in data from the parent when using ArrayObjectParser. Any ideas on how to fix this issue? Please assist me. import { Component, OnInit, Inject, ViewChild, Input } from '@angular/core'; import { Form ...

Anticipating the desired data types for Jasmine arguments

Lately, I've been in the process of upgrading my Angular version from 10 to 13 in order to utilize TypeScript 4.6. However, during this upgrade, I made some errors with types in my tests and I'm wondering if others have encountered similar issues ...

What is the reasoning behind not allowing an empty object as the initial value for hooks?

I am encountering an issue with my setProd Hooks. export interface faceProduct { readonly title: string; readonly prodState: string; readonly shipping: string; readonly sold: string; readonly alt: string; readonly material: string; readonly ...

Strategies for eliminating nested subscriptions in the search for names

I need assistance with refactoring a component I created to search for GitHub users by login. The current implementation contains nested subscribe blocks, and I would like to rewrite it using rxjs operators without nesting them. You can find the live exam ...

The error message "The function 'combineLatest' is not found on the Observable type"

Hey there! I'm currently working on implementing an InstantSearch function into my website using Angular 12.2. To accomplish this, I'll be working with a Firestore database with the index "book-data". In my search component, I have included the f ...

Typescript raises an issue regarding a React component's optional prop potentially being undefined

I have a basic React component that looks like this: interface ComponentProperties { onClick?: () => void; } const CustomComponent = (properties: ComponentProperties) => { if (!properties.onClick) { return <></>; } ...

What is the best way to confirm the invocation of super in sinonjs?

My JavaScript/TypeScript class (AAA) extends another class (BBB). The API of class BBB is stable, but the implementation is not yet finalized. I just want to unit test some functions in class AAA. However, I'm facing an issue in creating an instance o ...

The AngularJS Cross-Origin Resource Sharing (CORS) Policy

Our team is currently working on a web application using AngularJS that requires calling REST API services from another application. However, due to it being a cross domain request, we are facing difficulties in making the calls and receiving the following ...

Can you explain the distinction between 'bigint' in lowercase and 'BigInt'?

Currently, I am in the process of updating some TypeScript code that utilizes an external library for handling big numbers to BigInt (ES2020). However, the linter is throwing numerous errors which I find quite perplexing. https://i.sstatic.net/VnQSK.png ...

Error in TypeScript when utilizing an Enum as a string

Attempting to include a string enum in my Angular 2 project resulted in an error during the npm project startup: ERROR in e:/projects/dbtool-fullstack/dbtool-client/src/app/shared/models/full-m odels/enums/Sex.ts (2,10): Type '"Male"' is not ass ...

Encountering a CastError while attempting to send a POST request using Postman

I'm encountering a CastError when attempting to send a POST request using Postman. Why am I unable to simply send the patient and provider fields as strings? Should I refer to this documentation for guidance? I've come across some solutions, but ...

Creating a Type in Typescript that Inherits Keys from Another Type

Imagine you're faced with this scenario involving a Typescript class: class Person { name: string; age: number; } If you were to create an object type with the same properties, using the any type, but with all properties being optional - how wou ...

TSLint has flagged issues related to the generic Handler

When working with TypeScript, I make use of an event dispatcher to manage events within classes. While my code functions properly, TSLint raises concerns about the way I declare the handler, leaving me puzzled by its feedback. The following is a snippet o ...

Creating non-changing identifiers with ever-changing values in Angular by leveraging TypeScript?

I need to transform all the labels in my application into label constants. Some parts of the HTML contain dynamic content, such as This label has '1' dynamic values, where the '1' can vary based on the component or a different applicat ...

Issue with updating boolean values in reactive form controls causing functionality to not work as expected

I am currently facing an issue with validating a group of checkboxes. The main problem is that even though the 'this.dataService.minRequired' variable updates in the service, the validation state does not reflect these changes. I initially though ...

Utilizing class-validator for conditional validation failure

Implementing conditional validation in the class-validator library using the given example, I need to ensure that validation fails if the woodScrews property is assigned a value when the tool property is set to Tool.TapeMeasure. I've searched extensiv ...

Why does TypeScript require a generic type parameter when arguments have already been provided?

When I attempted to use the argument p to infer type P, TypeScript still prompted me to provide type P. Why is that? const numberStringConverter = <T extends string | number,P extends {x: any}>(p: P): T => { if(typeof p.x === 'string') ...

The distinctUntilChanged function encounters an issue when no comparison function is given

considering the following code: /** * Generating a stream of car objects from an array. */ from([ { name: 'Porsche', model: '911' }, { name: 'Porsche', model: '911' }, { name: 'Ferrari', model: &apo ...

How to fetch a file from a Spring Boot server using Angular 4

I'm currently developing a Spring Boot server with an Angular 4 front-end. I've created a service that allows users to download a .zip file from the front-end using HttpClient. Below is my code: Angular service: getZip(fileName: string) : Obser ...

Is it still necessary to use the ES6 module loader now that TypeScript 1.5 has integrated ES6 modules?

Can the separate ES6 module loader still required for the Angular 2 demo now that TypeScript 1.5 includes this syntax? Any suggestions on how to implement it without the additional loader? <head> <title>Angular 2 Quickstart</title> ...