[Fixed] how to create two branches for a observable pipe. I am not talking about iif

Issue

Let me explain. I have a subscription that returns an object with properties. The history property usually fetches a string, but it can also be null. How could I deal to separate 2 branches. I mean, if the value of the history property is a string, return it, if it is null display ‘No history’. I am aware of operator iif, but in this case the doubt is not about a conditional which retrieve one or another observable, I mean inside the same observable flow.

this.historyResult$ = this.historyObject$.pipe(
                            pluck('history')
                            );

To sum up: My question is, could I set something like a conditional to say: if the value of history is null then for example user the operator mapTo (‘No history’) in order to retrieve ‘No history’ string???

Solution

you could simply use a map operator. If x.history is undefined then the nullish coalescing operator ?? returns the string "No history" by the anonymous function inside of map. So that either the history property or the string is emitted:

this.historyResult$ = this.historyObject$.pipe(
  map((x) =>
    x.history ?? "No history"
  ),
);

Leave a Reply

(*) Required, Your email will not be published