RxJS Tip: Creation Function: of()

Deborah Kurata - Nov 16 '20 - - Dev Community

The RxJS of function is a creation function that emits specified values.

How Does It Work?

The of creation function takes in a set of values, creates an Observable that emits those values, and completes.

The Observable created with of is synchronous, meaning the values are emitted and it completes immediately after it is subscribed.

Alt Text

The above example passes three strings to the of function and subscribes.

Each of the three strings are then emitted and logged.

What Are Some Common Uses?

Sample code to try out a pipeline of operations.

of(1, 2, 3)
Enter fullscreen mode Exit fullscreen mode

User selects items for processing (ids of products in a cart, ids of selected songs for a playlist, etc.) and those items are emitted from an Observable.

of(45, 72, 21)
Enter fullscreen mode Exit fullscreen mode

For branching when one branch returns an Observable and another returns a static value as an Observable (such as null, an empty array, or an initialized value).

of(null)
of({})
of(this.initializedProduct())
Enter fullscreen mode Exit fullscreen mode

As a more concrete example of branching:

  getProduct(id: number): Observable<Product> {
    if (id === 0) {
      return of(this.initializeProduct()); // <-- of() used here
    }
    const url = `${this.productsUrl}/${id}`;
    return this.http.get<Product>(url)
      .pipe(
        tap(data => console.log(JSON.stringify(data))),
        catchError(this.handleError)
      );
  }
Enter fullscreen mode Exit fullscreen mode

This ensures that each branch returns an Observable.

NOTE: This example is meant to show usage of of() and is NOT meant to show the best technique to accomplish this objective.

Where's the Code?

Here is a link to sample code demonstrating the of creation function. Feel free to fork it and try it out.

What About the Marble Diagram?

This is the of creation function shown on a marble diagram:

Alt Text
Thanks to @michael_hladky for this marble diagram.

Do you have another common use of of? If so, please leave a comment.

Enjoy!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player