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

When using `type B = A`, B is represented as A. However, if `type B = A | A` is utilized, B appears as 'any'. What causes this change in representation?

import { C } from "https://example.com/type.d.ts"; type D = C | C Playground Upon hovering over D in both the TS Playground and VS Code, it will show as C when declared as type D = C, but display any when declared as type D = C | C. Even if C&a ...

Having trouble with ng build optimization error in Angular?

While developing a real-time chat application using Angular 13, I encountered an issue when trying to build the app for testing on my Node.js web server: ng build Every time I run this command, I receive an error in the console. Here is a screenshot of ...

typescript/raven.d.ts, at line 205, is throwing an error stating that it cannot recognize the name 'unknown' when attempting to install npm in an Ionic

During my work on an ionic project, I encountered this error while attempting to run npm install. You can access the package.json file through this link: ...

Factory function with type constraints and default parameter causing TS2322 error

I have a base class that requires some parameters to be passed... class BaseClass<ItemType> { // Some irrelevant parameters omitted for simplicity... constructor(__items: Iterable<ItemType>) {} } Now, I want to create a factory func ...

Exploring NestJS: Leveraging the @Body() Decorator to Retrieve Request Body Data

import { Controller, Post, Body } from '@nestjs/common'; import { MyService } from 'my.service'; import { MyDto } from './dto/my.dto'; @Controller('my-route') export class MyController { constructor(private rea ...

Obtain canvas context within Angular from within a Web Worker

I am currently using platformWorkerAppDynamic to showcase my Angular application, but I am facing a challenge when trying to manipulate the canvas context. Though I can create a canvas using Renderer2, I am struggling to find a way to call the getContext(& ...

Generating ng2 chart data dynamically within Angular 4

In my latest project, I've developed an application that retrieves data from a service in JSON format and displays it on a UI chart. However, I've encountered a recurring issue where the data does not bind properly to the chart despite multiple ...

What causes a union with a conditionally assigned property to lead to more relaxed types than anticipated?

Take a look at this TypeScript code snippet: const test = Math.random() < 0.5 ? { a: 1, b: 2 } : {}; Based on the code above, I would assume the type of object 'test' to be: const test: { a: number; b: number; } | {} This is the most str ...

The use of credentials is not allowed when the ‘Access-Control-Allow-Origin’ CORS header is set to ‘*’

My Java web application makes CORS requests where the browser performs an OPTIONS preflight before the actual request. The format of each request is as follows: Host: localhost:8080 User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/2 ...

What causes the "This page isn't responding" error to pop up in Edge and Chrome browsers while attempting to perform consecutive tasks in a web application built with Angular 8?

Trouble with Page Loading Whenever this error occurs, I find myself unable to perform any activities on that page. The only solution is to close the tab and open a new one. My current code allows me to navigate through an array list (Next and Previous) us ...

Retrieve identification details from a button within an ion-item located in an ion-list

<ion-list> <ion-item-group *ngFor="let group of groupedContacts"> <ion-item-divider color="light">{{group.letter}}</ion-item-divider> <ion-item *ngFor="let contact of group.contacts" class="contactlist" style="cl ...

Pyramid CORS does not support the PUT and DELETE HTTP methods

My current issue involves the pyramid framework. I have added a function to pyramid add_cors_headers_response_callback(event): def cors_headers(request, response): response.headers.update({ 'Access-Control-Allow-Origin': &ap ...

Angular 2 RC6: Exploring Parent-Child Interaction Using Event Emitters

Could someone provide an example that illustrates the concept of parent-child interaction using event emission in Angular2-rc6 (which no longer utilizes directives)? I have noticed that many online resources still reference the use of directives, which i ...

I'm encountering an issue where Typescript is unable to locate the Firebase package that I

I have a TypeScript project that consists of multiple .ts files which need to be compiled into .js files for use in other projects. One of the files requires the firebase package but it's not being found. The package is installed and located inside t ...

The functionality of MaterializeCSS modals seems to be experiencing issues within an Angular2 (webpack) application

My goal is to display modals with a modal-trigger without it automatically popping up during application initialization. However, every time I start my application, the modal pops up instantly. Below is the code snippet from my component .ts file: import ...

What is the best way to utilize a single npm module in multiple TypeScript files?

Question: I keep encountering the error message "error TS2451: Cannot redeclare block-scoped variable 'os'" when I try to import the same npm module in multiple TypeScript files and run the TypeScript compiler tsc. Here is an overview of my proj ...

Tips for successfully sending an API request using tRPC and NextJS without encountering an error related to invalid hook calls

I am encountering an issue while attempting to send user input data to my tRPC API. Every time I try to send my query, I receive an error stating that React Hooks can only be used inside a function component. It seems that I cannot call tRPC's useQuer ...

Tips for arranging datasets in React Chart.js 2 to create stacked bar charts

Currently, I am facing an issue with sorting the datasets displayed in each stacked bar chart in descending order as they are showing up randomly. Here is the snippet of my code: import React from 'react'; import { Chart as ChartJS, CategoryS ...

Exploring the power of Async/Await with Angular 5 HttpClient and forEach

I am struggling to implement async/await in my code to show a spinner when I click on a button and hide it once I have all the data. Below is a simplified version of what I have: .ts: isLoading: boolean = false; onLoad() { this.isLoading = true; ...

Tips for integrating Material-Ui Autocomplete with Formik's Field component to create Multi-Select check boxes

Trying to integrate Formik's Field component with Material-Ui Autocomplete for multiple values that include checkboxes has been challenging. Whenever a value is selected from the dropdown list, the popup closes and needs to be reopened for the next se ...