RxJS defaultIfEmpty() Conditional Operator
RxJS defaultIfEmpty() operator is a conditional operator used to emit a given value if the source observable completes without emitting any next value. Otherwise, it mirrors the source observable. It returns the values emitted by the source observable or a specified default value if the source observable is empty.
In other words, we can say that the RxJS defaultIfEmpty() operator returns a default value if it gets the source observable empty.
Syntax:
Following is the syntax of the RxJS defaultIfEmpty() conditional operator:
Or
Parameter Explanation
- defaultValue: The defaultValue argument is used to provide some values or if not given it is null by default. It is an optional argument. Its default value is null.
Return value
The RxJS defaultIfEmpty() operator returns an observable that emits either the specified defaultValue if the source Observable is empty (emits no items) or the values emitted by the source Observable.
Let us see some examples of the RxJS defaultIfEmpty() operator to understand it clearly.
Example 1 (Default for empty value)
Output:
After executing the above example, you will see the following result:
Example 2
Output:
After executing the above example, you will see the following result:
Example 3 (Default for Observable.empty)
Output:
After executing the above example, you will see the following result: