Uncomplicating RxJs Operators: Decoding switchMap and combineLatest

I currently have the following RxJS subscription :

combineLatest([obs1$, obs2$])
  .pipe(
     filter(val=>!!val[0] && !!val[1]), // ensuring no null values on both observables
     switchMap(([val1, val2]) => combineLatest([of(v1), getObs3$(v2)]))
   )
   .subscribe(([val1, val3]) => { ... });

Although the code functions as intended, it seems a bit cumbersome. I am certain that the switchMap into combineLatest with an of() operator can be improved.

Note : To call getObs3$(v2), I need to ensure that there is a value in obs1$ first. Additionally, I require the val1 in the subscription as I will be using it later on.

Does anyone have any ideas on how to optimize this?

Answer №1

Consider this approach:

combineLatest([source1$, source2$]).pipe(

  // ensure no null values for both
  filter(value=>!!value[0] && !!value[1]),

  switchMap(([value1, value2]) => fetchObs3$(value2).pipe(
    map(result3 => [value1,result3])
  ))

).subscribe(([result1, result3]) => { ... });

This is a common structure used frequently in these scenarios. We are adding result3 to a tuple here, similar to combine latest, but the same logic would apply if enriching an object (regardless of its depth).

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

Issue with Angular App: Bootstrap navbar not displaying on smaller screens

I am working on an Angular app (using Angular 11.2.4 with Bootstrap 4.5.3) and facing an issue where the navbar is not rendering correctly on screens smaller than ~580 pixels wide. Even when I click the toggler to 'expand' the collapse region, n ...

The combination of React Vite and SockJS Client has encountered a failure in all transport

My current project is utilizing react + vite without any proxy configuration. I am attempting to use webstomp-client and sockjs to establish a connection with a websocket server that is supported by Springboot using SockJS. The backend Springboot server w ...

Set panning value back to default in Ionic

I need assistance with resetting the panning value. Essentially, I would like the panning value to return to 0 when it reaches -130. Below is my code snippet: swipeEvent($e) { if ($e.deltaX <= -130) { document.getElementById("button").click(); ...

Assembly of these elements

When dealing with a structure where each property is of type These<E, A> where E and A are unique for each property. declare const someStruct: { a1: TH.These<E1, A1>; a2: TH.These<E2, A2>; a3: TH.These<E3, A3>; } I inte ...

Embracing Typescript promises over jQuery deferred for improved code efficiency and reliability

Currently, I have the following lines of code that utilize the JQueryDeferred object from the type definition class jquery.d.ts. My goal is to replace jQuery deferred with TypeScript promises. Here is the existing JQueryDeferred code: class A { privat ...

Where does tsc retrieve its definitions from when utilizing npm definitions?

After transitioning from using typings to just relying on npm, I noticed that the @types directory in node_modules is present, but there are no additional files required. Previously with typings, I always had to include the index.d.ts file within the typi ...

A single pledge fulfilled in two distinct ways

My code ended up with a promise that raised some questions. Is it acceptable to resolve one condition with the token string value (resolve(token)), while resolving another condition with a promise of type Promise<string>: resolve(resultPromise); con ...

Determine the category of a container based on the enclosed function

The goal is to determine the type of a wrapper based on the wrapped function, meaning to infer the return type from the parameter type. I encountered difficulties trying to achieve this using infer: function wrap<T extends ((...args: any[]) => any) ...

Managing updates with the spread syntax: Dealing with undefined or null properties

Let's take a look at this example method: GetCustomerWithPoints(customerId: number): Customer { const customer = this.customerService.getCustomer(customerId); const points = this.pointService.getPointsForCustomer(customerId); return {...custo ...

Utilize the imported function from <Script> within NextJS

When working with vanilla JS, I am able to include a script like this: <head> <script src="https://api.site.com/js/v1/script.js"></script> </head> and then create an instance of it using: const fn = ScriptJS(); I can t ...

Can you explain the purpose behind using this syntax within the subscribe function?

.subscribe(data=> { this.timezones = data; } Is the 'data' variable used in the .subscribe() method the same as the one declared in the constructor (private: data)? What does the arrow symbol mean and what is its purpose? export class X ...

Different varieties of TypeScript's keyof when working with objects

I am grappling with the concept of TypeScript's types when incorporating the keyof type operator on objects. Check out this example: type TypeA = { [k: number]: boolean }; type AKey = keyof TypeA; // ^? type AKey = number type TypeB = { [k: string] ...

Unable to assign unique identifiers to elements within a user interface framework

I am having difficulty assigning an id to components. Scenario 1: - Trying to assign an id to an HTML component. <h1 id="demo-h1">Demo Heading</h1> Assigning id to HTML component Scenario 2: - Attempting to assign an id to a componen ...

Transforming the color of the navbar upon a scrolling action is implemented through Angular's [ngClass

New to Angular and looking to implement a feature where the navbar changes from transparent to dark upon scrolling. However, my current implementation keeps the navbar transparent even after scrolling. Any tips on achieving this functionality? Here is the ...

A guide on integrating mat-select into Angular input fields

I've been trying to implement a mat-select dropdown on my input field, but for some reason, when I click on the arrow, nothing happens and the list doesn't show up. Usually, with autocomplete, when a user starts typing, all the options are displ ...

Could it be that the TypeScript definitions for MongoDB are not functioning properly?

Hello everyone, I'm facing an issue with getting MongoDB to work in my Angular 4 project. In my code, I have the db object as a client of the MongoClient class: MongoClient.connect('mongodb://localhost:27017/test', (err, client) => { ...

How can I customize the color of the disabled state in a mat-slide-toggle?

I am trying to customize the disabled state color of a mat-slide-toggle. This is what my slide toggle currently looks like: Here is the code I have been using: <div> <mat-slide-toggle>Slide me!</mat-slide-toggle> </div> Can any ...

Encountering the issue "Unable to define properties of undefined" during Angular unit testing tasks

When attempting to write a unit test case for a dropdown, an error is encountered: TypeError: Cannot set properties of undefined (setting 'ReferralCodes') .spec.ts it("should update the action selecting a value from category drop down", ...

Bring in Event Types from React using TypeScript

Is there a way to import Event Types from React and use them in Material-ui? Specifically, I am looking for guidance on how to import KeyboardEvent so that it can be utilized for onKeyDown callback type annotation. I have examined the .d.ts file of Mater ...

Before the service call finishes, Akita queries this.selectAll and returns an empty list

Here is the code snippet from my file named widgetquery.ts: @Injectable({ providedIn: 'root' }) export class WidgetQuery extends QueryEntity<WidgetState, WidgetTO> { public Widget$: Observable<WidgetTO> = this.selectActive().filter( ...