Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 - Observable explanation in plain English

I'm looking for a plain English explanation of what an Observable is in RXJS.

What it can be used for, and any useful explanations either video links, tutorials, use cases, examples, or anything really.

So far nothing I have found on Udemy, Todd Motto, Youtube, Angular official website has clicked with me and I just want a basic explanation of the above if that is possible.

So far all I know is that you can subscribe to them with an observer. Is it just another kind of variable?

Thanks in advance.

like image 458
Des Cahill Avatar asked Sep 24 '18 00:09

Des Cahill


People also ask

What is the use of Observable in Angular 6?

Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example: The HTTP module uses observables to handle AJAX requests and responses. The Router and Forms modules use observables to listen for and respond to user-input events.

What exactly is Observable in Angular?

Observables provide support for passing messages between parts of your application. They are used frequently in Angular and are a technique for event handling, asynchronous programming, and handling multiple values.

How we can use Observable in Angular?

Define and create observables in Angular To create an observer is simple in Angular, unlike the previous example where we defined everything from scratch. Here, we call the already defined class Observable from the RxJs and then pass the necessary arguments, as we will see shortly.

What is Observable observer?

Observer : Any object that wishes to be notified when the state of another object changes. Observable : Any object whose state may be of interest, and in whom another object may register an interest.


5 Answers

Lets start with promises

In Javascript, Promises are a common pattern used to handle async code elegantly. If you don't know what promises are, start there. They look something like this:

todoService.getTodos() // this could be any async workload
.then(todos => {
  // got returned todos
})
.catch(err => {
  // error happened
})

The important parts:

todoService.getTodos() // returns a Promise

Lets forget about how getTodos() works for now. The important thing to know is that lots of libraries support Promises and can return promises for async workloads like http requests.

A Promise object implements two main methods that make it easy to handle the results of the async work. These methods are .then() and .catch(). then handles "successful" results and catch is an error handler. When the then handler returns data, this is called resolving a promise, and when it throws an error to the catch handler, this is called rejecting.

.then(todos => { // promise resolved with successful results })
.catch(err => { // promise rejected with an error }) 

The cool thing is, then and catch also return promises so you can chain them like this:

.then(todos => {
  return todos[0]; // get first todo
})
.then(firstTodo => {
  // got first todo!
})

Here's the catch: Promises can only resolve OR reject ONCE

This works out alright for things like http requests because http requests are fundamentally execute once and return once (success or error).

What happens when you want an elegant way to stream async data? Think video, audio, real-time leaderboard data, chat room messages. It would be great to be able to use promises to set up a handler that keeps accepting data as it streams in:

// impossible because promises only fire once!
videoService.streamVideo()
.then(videoChunk => { // new streaming chunk })

Welcome to the reactive pattern

In a nutshell: Promises are to async single requests, what Observables are to async streaming data.

It looks something like this:

videoService.getVideoStream() // returns observable, not promise
.subscribe(chunk => {  // subscribe to an observable
   // new chunk
}, err => {
  // error thrown
});

Looks similar to the promise pattern right? One major difference between observables and promises. Observables keep "emitting" data into the "subscription" instead of using single use .then() and .catch() handlers.

Angular's http client library returns observables by default even though you might think http fits the single use promise pattern better. But the cool thing about reactive programming (like rxJS) is that you can make observables out of other things like click events, or any arbitrary stream of events. You can then compose these streams together to do some pretty cool stuff.

For example, if you want to refresh some data every time a refresh button gets clicked AND every 60 seconds, you could set up something like this:

const refreshObservable = someService.refreshButtonClicked(); // observable for every time the refresh button gets clicked
const timerObservable = someService.secondsTimer(60); // observable to fire every 60 seconds

merge(
  refreshObservable,
  timerObservable
)
.pipe(
  refreshData()
)
.subscribe(data => // will keep firing with updated data! )

A pretty elegant way to handle a complex process! Reactive programming is a pretty big topic but this is a pretty good tool to try and visualize all the useful ways you can use observables to compose cool stuff.

note: this is untested pseudocode written for illustration purposes only

like image 151
tommybananas Avatar answered Oct 21 '22 00:10

tommybananas


For a laugh, this fictional story only for dummies like me to understand:

After 7 years of marriage, wonderful John still in love with beautiful Kate, but Kate's girlfriends all tell her to keep an eye on John who works longer and longer hours now in the office.

"I'll call you back, busy, work on it." So CALLBACK is what Kate always hears when she calls John, one call-out one call-back. Though sometimes not easy to keep track of things for John.

John loves Kate, he upgrades the wording and handling by saying "I PROMISE (to do call Kate back)!" THEN again Kate is pleased and she establishes a safenet to CATCH the unexpected response, a better way to organize than Callbacks.

Kate is very happy with John, but her girlfriends still gossip on it, especially technology is advancing. So they all tell Kate, "you'd better OBSERVE him..." John is now OBSERVABLE to Kate who jokes to her darling that she's SUBSCRIBE to him, meaning John can now response continuously, no longer once, and can be multiple times, response can be streamed! Yulp, instead of one response per request, he sets up a little camera on his desk to keep her updated all the time. For example, Kate cares about his diet, he'd report "honey I just had a piece of cheese cake and an apple for breakfast", ... "honey I had a yummy lunch from ..." Lovely!

The END

like image 35
Jeb50 Avatar answered Oct 21 '22 01:10

Jeb50


It's like an event, by subscribing you are saying "let me know when this happens..".. so let's say you do a http request, you dont really know how long it will take, so the observable is just a placeholder or event you can subscribe to, which says when this happens, do something. That is, When this http request comes back, whenever that happens to be, read the value. The function you subscribe with will be run when it comes back.

like image 3
Dan Chase Avatar answered Oct 20 '22 23:10

Dan Chase


My understanding of Observable is like you ask Siri (or other stuff) "what is the weather tomorrow". Siri will give you the answer for sure and that 'item' inside Siri which contain the answer is 'Observable'.

Below link might be helpful - Demystifying Rxjs Observable

https://medium.com/@AnkurRatra/demystifying-rxjs-observable-467c52309ac

like image 2
Chao Wu Avatar answered Oct 21 '22 00:10

Chao Wu


Observables are like Twitter accounts. If we follow("subscribe") then we get notified with future updates, if we unfollow("unsubscribe"), then we won't be notified with future updates.

like image 1
Miguel Ormita Avatar answered Oct 21 '22 00:10

Miguel Ormita