Function input custom operator in RxJs

I am currently working on developing a custom rxjs operator. My previous custom operators, such as MonoTypeOperatorFunction or the regular Observable that accepts input like strings or numbers, have been successful. However, I am facing a challenge with creating an operator that can take in an anonymous function or predicate.

For instance, I am interested in creating an operator that is able to flatten elements within an object.

interface B {
  bid: number;
}

interface A {
  aid: number;
  bs: B[];
}

const b1: B = { bid: 1 };
const b2: B = { bid: 2 };

const a1: A = { aid: 1, bs: [b1, b2] };

const a1$ = of(a1);

// My goal is to merge map and concatMap into a single operator
const result = a1$.pipe(
  map(x => x.bs),
  concatMap(x => x)
).subscribe(x => console.log(x))
// OUTPUT: {bid:1}, {bid:2}

// Desired syntax
// a1$.pipe(many(x => x.bs))

// Attempt at creating the operator
// function many<T>(predicate: (input: T) => boolean) {
//   return function<T1>(source: Observable<T1>) {
//     return source.pipe(map(predicate),concatMap(x => x));
//   };
// }

Answer №1

There's a convenient operator that merges map and concatMap into one called concatMap.

Using

pipe(map(somefunc), concatMap(x => x))
is essentially the same as using concatMap(somefunc). This is why it's named concatMap ;)


Your function:

The function you created can be simplified like this:

function many<T>(predicate: (input: T) => boolean) {
  return pipe(map(predicate), concatMap(x => x));
}

which is equivalent to

function many<T>(predicate: (input: T) => boolean) {
  return concatMap(predicate);
}

By analyzing this, it becomes clear that you are converting your stream from type T to type boolean. Since concatMap requires a function with signature (input: T) => Observable<R>, not just a boolean, adjustments are needed. Thankfully, the input signature for concatMap aligns perfectly.

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

How do I adjust brightness and contrast filters on a base64 URL?

When presented with an image in base64 format like this: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDAAwfqNRk/rjcYX+PxrV/wtWqwJSTlboMgAAAABJRU5ErkJggg== What is the most efficient method to programmatically alter a filter (such as brightness or cont ...

Guidelines on adjusting Angular mat-button attributes using an observable stream

Below is the code snippet I am working with: <button mat-button [disabled]="offline() | async" [textContent]="scanning() ? 'Stop' : 'Start'" (click)="scanning() ? onScanStop() : onScanStart()"> </button> The functi ...

Adjusting the date in Angular 8 by increasing or decreasing it in the dd-MM-yyyy layout with a button press

How can I dynamically adjust the date in an input box by using buttons to increment and decrement it? Below is the code snippet: prev() { let diff = 1; //1 to increment and -1 to decrement this.date.setDate(this.date.getDate() - diff ...

When item.id matches group.id within the ngFor loop, a conditional statement is triggered

Creating nested columns with matching ids using ngFor seems like a challenge. How can I achieve this? Imagine having an object structured like this: columnNames = [ {id: 0, name: 'Opened'}, {id: 1, name: 'Responded'}, {id: ...

Issue encountered with ng-include compatibility in Angular 5

Just getting started with Angular and working on a small test project using Angular 5 and Visual Code. I'm attempting to use ng-include but the template is not displaying. src add-device add-device.component.html add-device.com ...

Data binding in Angular 2: Connecting components

Is it possible to establish a connection between two components that are working with related objects? One of the components is dedicated to filtering, while the other displays the data results. By applying filters such as checkboxes, the displayed data ...

The battle of ng-bullet and karma-parallel: optimizing Angular unit test performance with test module configuration in before all block

I'm currently exploring different options to enhance the speed of my unit tests in an Angular project. After reading several blogs, I came across some suggestions: (1) ng-bullet (2) karma-paralle (3) ng test --browsers ChromeHeadless (4) configu ...

Type 'ɵɵComponentDeclaration' must be provided with at least 7 but no more than 8 type arguments

Recently, in my project, I encountered an issue with the ng-particles v3.5.3 library on my login and sign-in pages. The problem arose suddenly and was displayed in my terminal as follows: Error: node_modules/ng-particles/lib/ng-particles.component.d.ts:18: ...

The server is taking too long to respond, resulting in a 504 Timeout error

I currently have an Angular frontend paired with a .NET CORE backend. The issue I am experiencing is related to a specific request that is resource-intensive and takes a significant amount of time to complete. Whenever I check the browser console, I receiv ...

The property 1 cannot be added because the object is not extendable in React

Does anyone know what is causing the following issue? I am unable to insert a new object into a key object within my arrays of objects. For example, when I try to insert a new email at index 1 in the 'emails' array, it throws an error stating "ca ...

What is the process for sending data to the backend using an HTTP POST request? The frontend is built with Angular 2 and the backend is developed with .NET

Having trouble with this error message: Error: XMLHttpRequest cannot load "http://localhost:49873/api/home". The response to the preflight request failed the access control check. There is no 'Access-Control-Allow-Origin' header present on the ...

Simplify an array in Javascript

I have a collection of objects structured in the following way: let list = [ { 'items': [ 'item 1', 'item 2' ] }, { 'items': [ 'item 3' ] } ] My goal is to flatte ...

The functionality of ZoneAwarePromise has been modified within the Meteor framework

After updating to the latest Angular 2.0.1 release on Meteor 1.4.1.1, I'm facing an error that says: Zone.js has detected that ZoneAwarePromise (window|global).Promise has been overwritten I've attempted running meteor update and meteor reset, b ...

What is the solution to the error message "Uncaught TypeError: createTheme_default is not a function"?

While working on my react application with vite, typescript, and mui, I encountered the following error: enter image description here This issue seems to be connected to material ui. Sometimes, deleting the 'deps' folder in '\node_mod ...

The Angular Component utilizes the ng-template provided by its child component

I am currently facing an issue that involves the following code snippet in my HTML file: <form-section> <p>Hello</p> <form-section> <ng-template test-template> TEST </ng-template> ...

MAJOR UPDATE: webpack versions before 5 previously contained polyfills for node.js specifically for 'timers-browserify'

Hey there, I'm encountering the error message below: ./node_modules/xml2js/lib/parser.js:38:17-47 - Error: Module not found: Error: Can't resolve 'timers' in '/Users/differentname/Desktop/workfiles/webdoc/ngx-admin-1/node_modules/x ...

Is the async pipe the best choice for handling Observables in a polling scenario

The situation at hand: I currently have a service that continuously polls a specific URL every 2 seconds: export class FooDataService { ... public provideFooData() { const interval = Observable.interval(2000).startWith(0); return interval ...

Creating a Custom Form Control in Angular 2 and Implementing Disable Feature

I have developed a unique custom control using ControlValueAccessor that combines an input[type=text] with a datepicker. While the template-driven forms accept it without any issues, the situation changes when implementing the model-driven approach (react ...

What is the best way to display a JSON array in Angular 4?

Check out this JSON structure: -------------------------------------------------- "id": 2, "user": { "id": 1, "name": "User", "surname": "User", "email": "<a href="/cdn-cgi/l/email-protection" ...

Changing true/false values to Yes or No in Angular array output

I am working with an array that is structured as follows: { "Tasks": [ { "TaskID": 303691, "TaskName": "Test1", "TaskType": "Internal", "Status": "Processing", "IsApproved": false, "RowNumber": 1 }, { ...