OBSERVABLES, OBSERVERS & SUBSCRIPTIONS | RxJS TUTORIAL

OBSERVABLES, OBSERVERS & SUBSCRIPTIONS | RxJS TUTORIAL

Introduction to Observables, Observers, and Subscriptions

In this section, we will learn about observables, observers, and subscriptions in RxJS. We will understand how these concepts work together to handle data streams.

Observables and Data Sources

  • An observable is a wrapper around a data source, typically representing a stream of values.
  • It can be used for both asynchronous and synchronous data sources.
  • The observer is responsible for executing code whenever a new value, error, or completion event occurs in the observable.
  • The observer needs to be connected to the observable through a subscription.

Observer Methods

  • The observer implements up to three methods: next, error, and complete.
  • The next method is called when a new value is emitted by the observable.
  • The error method is called when the observable throws an error.
  • The complete method is called when the observable is done emitting values.

Observable-Observer Contract

  • Through the subscription, the observable knows it can invoke next, error, or complete on the observer.
  • The observer knows that the observable will only invoke one of these three methods.
  • This contract allows effective communication between observables and observers.

Stream Representation

  • Observables are commonly depicted as streams of values.
  • An observable wraps around a stream of values that can be synchronous or asynchronous.
  • Observers have methods to handle any number of values emitted by the stream.
  • An endpoint indicates when the observable has completed emitting values.

Handling Errors and Completion

In this section, we will explore how errors and completion events are handled in observables.

Completing an Observable

  • Some observables may never finish if they represent ongoing processes.
  • However, if an observable has a definite endpoint, we can call the complete method to indicate that no more values will be emitted.

Handling Errors

  • Observables can also emit error events in addition to values.
  • For example, an observable wrapping an HTTP request may throw an error if there is a timeout or server-side issue.
  • The observer's error method can handle these error events.

Example Usage of Observables

In this section, we will see how observables are used in code through an example.

Using RxJS on JSFiddle

  • The speaker demonstrates using RxJS on JSFiddle for the example.
  • The RxJS package is imported from the CDN and a button element is added to the HTML.
  • An observable is created using the fromEvent helper method, which wraps around the click event of the button.

Subscribing to Observables

  • The subscribe method is used to subscribe to the observable and pass an observer as an argument.
  • When the button is clicked, the observer receives and handles the emitted value (the x position of the cursor).

Conclusion

Observables, observers, and subscriptions are fundamental concepts in RxJS. Observables wrap around data sources and emit values over time. Observers handle these values, errors, and completion events. Subscriptions connect observers to observables. By understanding these concepts, developers can effectively work with asynchronous data streams in their applications.

Creating Observables with JavaScript

In this section, we learn how to create observables in JavaScript using the create method. We explore the different functions that can be used with observables, such as next, error, and complete.

Creating an Observable from Scratch

  • To create an observable from scratch, we can use the create method.
  • The create method takes a function as an argument, which in turn takes an observer object.
  • Inside the function passed to create, we can call the next method on the observer to emit a value.
  • We can also call the error and complete methods on the observer to handle errors and completion of the observable.
  • If an error occurs, the observable is finished and won't emit any more values.
  • If completion is called, the observable is done executing.

Understanding Asynchronous Observables

  • Observables don't have to be asynchronous by default. They can also be synchronous like in our previous example.
  • Asynchronous behavior can be achieved by wrapping something that is inherently asynchronous, like events, using methods like fromEvent.
  • Asynchronous observables provide a stream of data that makes more sense for certain scenarios.

Understanding Asynchronous Observables in JavaScript

In this section, we explore the behavior of asynchronous observables in JavaScript and how to create them using the create method. We also discuss the importance of unsubscribing from subscriptions to avoid memory leaks.

Default Set Timeout Behavior

  • The default setTimeout code executes after a specified delay.
  • When combining ops.complete with setTimeout, the output is different as it waits for two seconds before printing "completed."
  • JavaScript does not wait for a set timeout to finish; it continues executing other lines of code.
  • Asynchronous observables can have synchronous values emitted immediately, followed by an event occurring after a delay.

Creating Custom Observables

  • It is possible to recreate observable behavior using custom code.
  • By assigning an event listener function to a button's onclick event, we can create our own observable that emits events when clicked.
  • This demonstrates how observables work behind the scenes and how they can be built from scratch using the create method.

Memory Management and Unsubscribing

  • Subscriptions to observables should be unsubscribed when no longer needed to prevent memory leaks.
  • Storing subscriptions in variables or object properties allows easy access for unsubscribing.
  • Demonstrated by setting up a subscription and then calling the unsubscribe method after five seconds, which stops further value printing.

By understanding asynchronous observables, creating custom observables, and managing subscriptions properly, developers can harness the power of reactive programming in JavaScript effectively.

Video description

RxJS Observables are subscribed by Observers...Wait...what? Let's understand how that all works! Join the full Angular (it uses RxJS heavily!) course: https://acad.link/angular Exclusive discount also available for our Ionic + Angular course: https://acad.link/ionic Dive into the full RxJS Introduction series: https://academind.com/learn/javascript/understanding-rxjs/ Check out all our other courses: https://academind.com/learn/our-courses ---------- Code 1/2: https://jsfiddle.net/qhcumwy4/ Code 2/2: https://jsfiddle.net/2eefj8Ld/ ---------- • Go to https://www.academind.com and subscribe to our newsletter to stay updated and to get exclusive content & discounts • Follow @maxedapps and @academind_real on Twitter • Join our Facebook community on https://www.facebook.com/academindchannel/ See you in the videos! ---------- Academind is your source for online education in the areas of web development, frontend web development, backend web development, programming, coding and data science! No matter if you are looking for a tutorial, a course, a crash course, an introduction, an online tutorial or any related video, we try our best to offer you the content you are looking for. Our topics include Angular, React, Vue, Html, CSS, JavaScript, TypeScript, Redux, Nuxt.js, RxJs, Bootstrap, Laravel, Node.js, Progressive Web Apps (PWA), Ionic, React Native, Regular Expressions (RegEx), Stencil, Power BI, Amazon Web Services (AWS), Firebase or other topics, make sure to have a look at this channel or at academind.com to find the learning resource of your choice!