Observables are one of those new tricky things you will almost certainly run into at some point when building an application with Ionic 2. They can seem a little weird and overwhelming at first, and you might wonder ”why can’t we just stick to promises?”, but they are quite beautifully implemented. At a basic level, you don’t need to worry about all of the advanced things observables can do or what “reactive programming” is, you will mostly just need to know a few basics like how to subscribe to an observable.
In this video tutorial, I cover the basic concept of observables and how they are relevant to an Ionic 2 application.
Here’s the video:
Video Notes
- Observables are provided by the RxJS library – they are not specific to Ionic or Angular
- Observables are somewhat similar to promises, but they can do a lot more
- Observables can emit multiple values over time, rather than just resolving once
- You can
subscribe
to an observable to do things with the data that it emits - Observables are “lazy” meaning that they won’t be executed until they are subscribed to
- Multiple different operations can be applied to observables to modify the observable and return a new one
- The first observables you will likely run into when building Ionic 2 applications is through the
Http
service, or through an Ionic Native plugin - You can create your own observables, but at a beginner level this will not likely ever be necessary
- You can create your own observable using the following format:
let myObservable = Observable.create((observer) => {
observer.next('hello');
});
myObservable.subscribe((data) => {
console.log(data);
});
- A Subject combines the observer/observable pattern into one easy to use method, which you may prefer to use for simple implementations
- You can create a Subject with the following code:
let mySubject = new Subject();
mySubject.subscribe((data) => {
console.log(data);
});
mySubject.next('hello');