Manipulate streams using pipes

Is there a more elegant solution for handling this particular piece of code?

return new Observable(subscriber => {
    let subscription = this.anotherObservable().subscribe(
        (next) => {
            if (this.condition1(next)) {
                subscriber.next(next);
            } else if (this.condition2(next)) {
                subscriber.complete();
            } else {
                subscriber.error('there was an error');
            }
        },
        (error) => subscriber.error(error),
        () => subscriber.complete()
    );

    return () => subscription.unsubscribe();
});

This code is located within a method in a specific class.

The anotherObservable function returns an Observable that emits different types of data, hence the boolean conditions based on the value of next.

I'm curious if there are any operator combinations that could achieve the same behavior with this Observable using pipes instead of creating a "custom" Observable.

Answer №1

Combine takeWhile and flatMap in this way:

const sub = anotherObservable.pipe(
      takeWhile(val => !this.condition2(val)),
      flatMap(val => {
        if(this.condition1(val)) {
          return of(val);
        }
        return throwError('an error occurred');
      })
    ).subscribe(val => //perform an action with the value);

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

What is the process for adding my Ionic app to the share menu on an iPhone?

I'm working on an Ionic 3 app and I want it to be integrated into the iPhone share list just like shown in this example, https://i.sstatic.net/U2Lqr.png The Share option should appear when users access the gallery and then when they press the share b ...

typeorm migration:generate - Oops! Could not access the file

When attempting to create a Type ORM migration file using the typeorm migration:generate InitialSetup -d ormconfig.ts command, I encountered an error: Error: Unable to open file: "C:\_work\template-db\ormconfig.ts". Cannot use impo ...

Issue with TailwindCSS @apply not compiling in Angular v12 component styles

I am a computer science student working on a project for my studies. I am currently developing a component library for the Angular framework using Angular V12. To style the components, I have decided to use Tailwindcss as it simplifies some aspects like me ...

Concealing the TinyMce Toolbar upon initialization

After setting my content with tinymce, I want to make the toolbar readonly. To achieve this, I subscribed to the editor's init function like so: editor.on('init', () => { editor.setContent(this.value); if (this.disab ...

Using Angular's typeahead with RxJs switchMap for subscribing to data sources

Implementing the Angular bootstrap Typeahead plugin for displaying colors. However, I am facing difficulty in resolving circular references like I have done in other parts of my project. The RxJs SwitchMap operator is not working for me in this case. Are t ...

Obtain a personalized response from an Angular HTTP service

I'm trying to implement the following code directly in a component: if(exampleService.checkValidityOfToken()) { //do something } Here is the method in exampleService that corresponds to this. I'm not sure if I am returning the value properly or ...

`Why isn't GetServerSideProps being triggered for a nested page in Next.js when using Typescript?

I have been working on a page located at /article/[id] where I am trying to fetch an article based on the id using getServerSideProps. However, it seems that getServerSideProps is not being called at all as none of my console logs are appearing. Upon navi ...

Preserving hyperlinks while transferring text from an HTML element using JavaScript

I'm struggling to preserve links from HTML elements while copying rich text, but have been unable to achieve it despite numerous attempts. The following code represents my best effort so far, however it only copies text without maintaining the links ...

Could a template variable be established for the p-dropdown element in template-driven form validation?

In the template, I have a p-dropdown element <p-dropdown id="output-method" [options]="outputMethods" [(ngModel)]="transformer!.outputMethod" pTooltip="Output Method" tooltipPosition="bottom&quo ...

A guide on streamlining the process of generating "this." variables within Angular

When it comes to working with Javascript, particularly Angular, I find myself using the this. syntax quite often. I'm curious to know if it's possible to concatenate variables in order to create a this. variable. For instance, is this achievab ...

Incorporating unit measurements into input data

I am currently working on styling an input to only accept numbers while allowing the user to add a unit of measurement (such as kg, km, etc.) immediately after the value. I prefer not to use span because I want the unit measurement to appear as the user st ...

Refining the firestore collection based on a specific document attribute

I currently manage three collections: users, doctors, and reviews. Within my component.ts file, I have defined two arrays: Doctors: Doctor[]; Reviews: Review[]; I have displayed all the elements from the Doctors array using a *ngFor directive. doctor el ...

Creating a concise TypeScript declaration file for an established JavaScript library

I'm interested in utilizing the neat-csv library, however, I have encountered an issue with it not having a typescript definition file available. Various blogs suggest creating a basic definition file as a starting point: declare var neatCsv: any; M ...

What impact does setting 'pathmatch: full' in Angular have on the application?

When the 'pathmatch' is set to 'full' and I try to delete it, the app no longer loads or runs properly. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { H ...

Exploring the integration of Server-Sent Events in Angular

I'm currently working on incorporating Server-Sent Events (SSE) into my testing application. The server side configuration has been completed, and I am utilizing the endpoint (api/v1/sse/document). The aim here is that whenever a scan is performed, I ...

Converting input dates in nest.js using TypeScript formatting

Is it possible to set a custom date format for input in nest.js API request body? For example, like this: 12.12.2022 @ApiProperty({ example: 'ADMIN', description: 'Role name', }) readonly value: string; @ApiProperty({ ...

Design theme with Angular and Bootstrap styling

Working with Angular 5 and Bootstrap 4, I am attempting to create a customized style theme. Although my implementation is quite simple, it's not compiling as expected. src/style.scss : @function theme($key: "primary") { @return map-get($theme-colo ...

Is it planned to include StencilJS as a development choice in Ionic?

I'm curious about the potential adoption of Stencil JS for developing mobile apps within the Ionic framework. When I mention "an option for developing," I'm referring to frameworks like NativeScript where developers can choose between Angular + ...

The issue with ngx-bootstrap-modal is that it fails to interpret HTML elements

In my Angular 5 project, I am implementing ngx-bootstrap-modal. Below is the code I am using to open the modal: this.dialogService.addDialog(PopUpComponent, { title: 'Custom locale', message: "Hello ? " }).subscribe((isConfirmed ...

Leverage the power of OpenLayers 5's TypeScript extent.js within an Angular 7 environment

Currently, I am attempting to utilize the "extend" function from extent.js, which is housed under the "ol" library as a standalone file within my codebase. My initial approach was importing it in this manner... import olExtent from '../../../../../n ...