Watching - transforming / combining

I am a beginner when it comes to working with Observables. Here's the Effect that I am using:

My goal is to dispatch the PositionUpdateAction or PositionFailedAction before the SunriseSunsetAction is dispatched.

Currently, what happens is that the result of getCurrentPosition() is passed into the last map in the result variable, and then the SunriseSunsetAction is dispatched. Neither the PositionUpdateAction nor PositionFailedAction are being dispatched.

I believe that I need to incorporate concat in some way. I've tried different approaches but haven't been successful.

I would really appreciate any guidance or assistance on this matter.

@Effect()
  position$: Observable<Action> = this.actions$.pipe(
    ofType(ActionType.GetPosition),
    mergeMap(() =>
      fromPromise(this.geo.getCurrentPosition()).pipe(
        map(value => new UiActions.PositionUpdateAction(value)),
        catchError((err) => {
          return of(new UiActions.PositionFailedAction(err));
        })
      ).map(result =>
        new UiActions.SunriseSunsetAction(this.sun.calculateSunriseSunsetWindows(result.payload.lat, result.payload.long))
      )
    )
  );

Answer №1

I will provide a general solution to what I believe is the issue you are facing. The situation is typically where you have a task that produces a result, which you then want to use for another task. Ultimately, you want both results to be outputted.

In your specific case, the first task involves making a request and the second task involves mapping to another action.

The solution is to utilize *Map(...) (such as switchMap or mergeMap) to leverage the outcome of the first task for the second one. Instead of directly returning the observable from the second task, you can use concat to emit both outcomes in the desired order. Here is a generic example:

const { of, concat } = rxjs;
const { flatMap } = rxjs.operators;

of(1).pipe(
  flatMap((x) => concat(of(x), of(2)))
).subscribe((x) => { console.log(x); })
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.1.0/rxjs.umd.min.js"></script>

Therefore, your code may resemble something like this:

@Effect()
position$: Observable<Action> = this.actions$.pipe(
  ofType(ActionType.GetPosition),
  mergeMap(() =>
    fromPromise(this.geo.getCurrentPosition()).pipe(
      map(value => new UiActions.PositionUpdateAction(value)),
      flatMap((x) => concat(
        of(x),
        new UiActions.SunriseSunsetAction(this.sun.calculateSunriseSunsetWindows(result.payload.lat, result.payload.long))
      )),
      catchError((err) => {
        return of(new UiActions.PositionFailedAction(err));
      })
    )
  )
);

If you are using effects, another approach would be setting up another effect to listen for the PositionUpdateAction action. However, this could potentially create complex code...

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

Creating autorest client based on various OpenAPI versions

I'm currently exploring options for creating a Typescript client from our .NET API. After researching various tools, I decided to go with Autorest, as it is Node-based and fits my skillset. While I am aware of Swashbuckle, my knowledge leans more towa ...

Obtain a value that is not defined

Good day, I am encountering an issue with my data not accepting an undefined value. Below is the code snippet: interface IModalContatos { dados: IContatos; onSave(dados: IContatos): void; onClose(): void; } When passing this data to my modal, I rece ...

Converting an array of objects to an array of JSON objects in TypeScript

My dilemma lies in the data I have uploaded under the _attachments variable: https://i.sstatic.net/jnFNH.png My aim is to format this data for insertion in the following structure: "_attachments": [ { "container": "string", "fileName": "string" ...

What could be causing the module version discrepancy with the package.json file I created?

Recently, I created a project using create-next-app and decided to downgrade my Next.js version to 12. After that, I proceeded to install some necessary modules using Yarn and specified the versions for TypeScript, React, and others. During this setup, I b ...

What is the best way to utilize the fresh Sanitizer API in Typescript?

Everything seems to be working well on Codepen, even without using window. It's surprising because I'm used to having to use window.x if ( 'Sanitizer' in window ) { console.log( 'sani', 'Sanitizer' in window ); } ...

Distribute among an array of specific types

I am trying to achieve this behavior using Typescript: type animals = 'cat' | 'dog' let selectedAnimals: animals[] = ['cat'] selectedAnimals = [ // <- Type 'string[]' is not assignable to type 'animals[]&ap ...

The functionality of the String prototype is operational in web browsers, but it encounters issues

Version: 8.1.0 The prototype I am working with is as follows: String.prototype.toSlug = function () { return (<string>this) .trim() .toLowerCase() .replace(/\s+/g, '-') .replace(/[^\w\-]+/g, '') ...

Eliminating an element from an object containing nested arrays

Greetings, I am currently working with an object structured like the following: var obj= { _id: string; name: string; loc: [{ locname: string; locId: string; locadd: [{ st: string; zip: str ...

implementing a default reducer using ngrx schematics

I'm having trouble creating a reducer using the ngrx schematics command ng generate @ngrx/schematics:reducer ZipCodes --group When I generate the reducer file, it does not include a default implementation of the reducer export const reducer = createR ...

I need to verify that the input type for time is valid, starting from today's date and extending beyond the current

<input type="date" onChange={(e)=>setDate(e.target.value)}/> <input type="time" onChange={(e)=>setTime(e.target.value)} /> If the selected date is after today and the time is after the current time, display a valida ...

Exclude weekends from DateTime

Currently working on a task list and aiming to set the default date to 3 days from now, excluding weekends. Utilizing Vue and thinking a computed property might be the solution? DateTime.utc().plus({ days: 3 }).toFormat('yyyy-MM-dd HH:mm:ss'), ...

A guide on transforming a Firebase Snapshot child into a personalized object in a React Native environment

I'm looking for a way to retrieve data from Firebase Realtime Database and display it in FlatList format. What is the most efficient method for extracting the child value and converting it into a custom object? For example: class CustomObject { ...

Issue with setInterval function execution within an Angular for loop

My goal is to dynamically invoke an API at specific intervals. However, when attempting to utilize the following code snippet in Angular 7, I encountered issues with the interval timing. I am seeking a solution for achieving dynamic short polling. ngOnIn ...

I am curious about the types of props for the methods within the 'components' object in react-markdown

Having some trouble using 'react-markdown' in NextJs 13 with typescript. TypeScript is showing errors related to the props of the 'code' method, and after searching online, I found a solution that involves importing 'CodeProps&apos ...

Leverage es6 classes along with mongoose in typescript to utilize loadClass functionality

I've been struggling with a problem and despite my exhaustive search on Google, I still haven't found a solution. My issue revolves around incorporating es6 classes with mongoose using the schema.loadClass(class) method. Unfortunately, when worki ...

Encountered an issue loading resource: net::ERR_BLOCKED_BY_CLIENT while attempting to access NuxtJS API

After deploying my NuxtJS 2 app on Vercel and adding serverMiddleware to include an api folder in the nuxt.config.js file, everything was working smoothly. However, when I tried making an api call on my preview environment, I encountered an error: POST htt ...

Is there something I'm overlooking, or is this behavior unusual for an "if statement"?

I am facing an issue with returning a value from a function. It seems like a simple task - just looping through my HTMLElements and returning the one I need. This problem is new to me, and I have spent a considerable amount of time debugging the code and ...

Exploring the use of national flag emojis in VS code

I've been attempting to use flag emojis as reactions on a Discord bot, but they just won't cooperate. Every time I try something like this > ':flag_jp:', I encounter the following error: Error: DiscordAPIError: Unknown Emoji EDIT ...

Typescript: Extracting data from enum items using types

I am facing a challenge with an enum type called Currency. I am unable to modify it because it is automatically generated in a graphql schema. However, I need to utilize it for my data but I'm unsure of how to go about doing so. enum Currency { rub ...

What could be causing my Angular 7 header to be unresponsive?

I am facing issues with my http, header, and RequestOption in the API. I am working with Angular 7.1 and have tried various methods to resolve the problem without success. The error message I am receiving is: The token is not being passed in the header ...