Welcome back to CodeYourCraft! Today, we're diving into a crucial aspect of Angular: Observers and Subscriptions. This lesson is perfect for both beginners and intermediates. Let's get started!
In Angular, Observables are a way to handle asynchronous data streams, while Subscriptions allow us to listen to these streams. Let's take a real-world example to understand this better. Imagine a news ticker that fetches and displays the latest headlines. The news ticker (Observer) subscribes to a stream of news articles (Observable), listens for updates, and displays them.
import { Observable } from 'rxjs';
// Let's create an Observable that emits news headlines
function getNewsHeadlines(): Observable<string> {
return new Observable((observer) => {
// Simulate fetching news headlines
setTimeout(() => {
const headlines = ['Breaking News 1', 'Breaking News 2', 'Breaking News 3'];
headlines.forEach((headline) => observer.next(headline));
observer.complete();
}, 3000);
});
}
// Now, let's create a Subscription to listen to news headlines
const subscription = getNewsHeadlines().subscribe((headline) => {
console.log(headline);
});
// Our news ticker is now live!š” Pro Tip: In this example, getNewsHeadlines() returns an Observable that emits strings. The subscribe() method is used to create a Subscription that listens to the Observable and runs the callback function whenever a new value is emitted.
Managing Subscriptions is essential to avoid memory leaks. When a Subscription is created, it starts listening to an Observable. To stop listening, we need to unsubscribe from the Subscription.
// To unsubscribe, simply call the unsubscribe method on the Subscription object
subscription.unsubscribe();š” Pro Tip: If you're using Angular's HttpClient for making HTTP requests, it automatically unsubscribes from the Observable when the component is destroyed.
Fetching and Updating Data: Use Observables and Subscriptions to fetch data from a server and update the UI in response to changes.
Event Handling: Create custom events and subscribe to them to respond to user interactions.
Combining Observables: Use operators like mergeMap, switchMap, and forkJoin to combine multiple Observables.
What does an Observable do in Angular?
That's it for today! In the next lesson, we'll explore how to use RxJS operators to transform and combine Observables. Stay tuned! š