Angular 6 - Observable explanation in plain English
Asked Answered
Q

6

15

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.

Quechuan answered 24/9, 2018 at 0:39 Comment(3)
Perhaps the answers to this question may help https://mcmap.net/q/45060/-what-is-the-difference-between-promises-and-observables?rq=1Parmenides
Nice bit of info. Not really too sure what a promise is though, but I'll get there I'm sure.Quechuan
Been a while since I visited this post but O found this today in case it helps anyone else. medium.com/@luukgruijs/…Quechuan
S
43

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 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

Savil answered 24/9, 2018 at 2:39 Comment(3)
Wow thats a lot ofg info. Ill read though this in the morning. ThanksQuechuan
it's a big topic, but understanding the why is just as important as the what in my opinion. good luck!Savil
Man that explains everything and more. Thanks a lot for taking the time to explain this is in such detail. Thanks everyone else also, the variety of dfferent explanations also helped a lot.Quechuan
M
7

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

Misapprehend answered 17/7, 2019 at 23:45 Comment(2)
Thanks for making the effort :PQuechuan
Nice one !! Easily relatable !Prosper
I
3

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.

Inadequate answered 24/9, 2018 at 0:51 Comment(4)
So I subscribe to something and when that value is returned it triggers a particular function that I make? By any chance would you have a use case? I'm new to coding an mainly used Python but Im working with Angular6 at the moment and not getting a lot of these terms.Quechuan
Hi Des, the HTTP request is a great example, because your program is not going to just sit and wait for it to come back. In other languages/frameworks/etc you may have to do special things to make this happen, like l multithreading/etc.. but not here, it's expected.. So the observable is a strange name for an event you quickly setup, and the subscribe is basically a handler.. edit, let me add that if you're new to programming, Angular might not be the best place to start. Not meaning to start any discussion on this here on Stack Overflow, but the basics first, at least stick to 1 lang.Inadequate
Thanks Dan. Well Im new to working with coding, and my job is as a Junior Angular 6 Dev. In college I did a bit of AngularJS(Didnt like it), a lot of Python3 Django(Loved it), and Javascript (Didnt cover Arrow functions or Angular 2+). So Python and Javascript are my 2 preferences with Javascript/Typescript being my focus for the foreseable future. Realworld use cases will help me understand, but knowledge of not having experience will help me understand. When cheese gets eaten, mousetrap function is executed. Something like this.Quechuan
I wish you the best in your path!Inadequate
D
2

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

Discreditable answered 24/9, 2018 at 1:22 Comment(2)
A promise fits your model too. Not specific enoughSavil
The medium article is one of the best I've read yet, I've been struggling with this pattern as well and this helped a lot.Kenspeckle
O
1

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

Osier answered 27/8, 2021 at 13:57 Comment(0)
P
0

Observable is a feature in Angular which is used to handle asynchronous data.

Let's understand them in detail.

Angular uses the publishers and subscribers pattern. In this, there is an Observable which emits the data stream over time. The data can be either the HTTP response or it can be the event data when the button is clicked. And there is Observer which subscribes to that data(In other words, it observes the data source).

We can handle the observable in 3 ways. Firstly, we can handle the normal data which is emitted by observable. Secondly, we can handle the error. Thirdly, we can handle the completion of observable.

NOTE: Observable doesn't publish the data until an observer subscribes to it. If the observer doesn't want to observe anymore, it can unsubscribe from the observable.

Polygnotus answered 29/12, 2021 at 6:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.