Home > Software design >  How to return data from first observable despite error inner?
How to return data from first observable despite error inner?

Time:10-22

I have two streams one by one:

  .pipe(
                   
                    map(() => new SemanticObject(this.objectLayer, this.map)),
                    concatMap((semanticObject: SemanticObject) =>
                        from(semanticObject.saveObject(semanticObject.getObject())).pipe(
                            concatMap(() => semanticObject.changeObjectStateUnom()),
                            map((data) => data;
                        ),
                    ),
                )

I try to return data from first stream here map((data) => data;. despite if concatMap is failed. How to do that?

I have tried this:

.pipe(
                    tap(() => this.loading$.next(false)),
                    filter(Boolean),
                    map(() => new SemanticObject(this.objectLayer, this.map)),
                    concatMap((semanticObject: SemanticObject) =>
                        from(semanticObject.saveObject(semanticObject.getObject())).pipe(


                            concatMap((updatedObject: ObjectLayer) => semanticObject.changeObjectStateUnom().pipe(
                                catchError((updatedObject) => updatedObject),
                                mapTo(updatedObject)
                            )),
                        ),
                    ),
                )

CodePudding user response:

You're so close! CatchError is a higher-order operator (like concatMap, but for errors), so you need to return an observable.

For example:

pipe(
  tap(() => this.loading$.next(false)),
  filter(Boolean),
  map(() => new SemanticObject(this.objectLayer, this.map)),
  concatMap((semanticObject: SemanticObject) =>
    from(semanticObject.saveObject(semanticObject.getObject()))
  ),
  concatMap((updatedObject: ObjectLayer) => 
    semanticObject.changeObjectStateUnom().pipe(

      catchError(error => of("Error Token")),
      map(changedState => 
        changedState === "Error Token" ? 
        updatedObject : changedState
      )

    )
  )
);

Of course, using a string as an error token isn't idiomatic, but you can choose whatever works best for you.

  • Related