Observable, when to use?

Why and when should I use Observable, what are its advantages and disadvantages and its difference compared to Promisses?

Author: Marciano Machado, 2019-01-09

2 answers

Brought this article that was published by Wendel Birth that I found so you can see not only what it is more also how to use, maybe you understand better.

Link from where I got the reference for you to check the full article.: https://tableless.com.br/entendendo-rxjs-observable-com-angular /

What is an Observable?

By definition is a collection that works unidirectionally, that is, it issues notifications whenever a change occurs in one of its items and from that we can perform an action. Let's say it solves the same problem that the previous version of Angular had solved with $watch, but without using brute force. While in $watch we check our entire scope for changes after each $digest cycle (which has a great cost in performance), with Observable this check does not happen, because for each event a notification is issued to our Observable and then we treat the give.

What do I do with Observable? And Where does Angular come into this story?

Let's imagine the consumption of a web service, something very common in Single Page application, before Observable we would do this way

getUsers(): Promise<User[]>{
  return fetch(myApiUrl)
  .then(res=>res.json())
  .catch(err=> Observable.throw(err.message));

} The above code is quite simple, we are looking for a resource (a list of users) and after the answer we turn everything into JSON.

However, the new Angular was built with reactive applications in mind, abandoning the use of Promises and adopting default the Observable.

Using Observable the same function would look like this:

@Injectable()
class UserService {
 ...
 getUsers(): Observable<User[]> {
    return this.http.get(myApiUrl)
                    .map(res=>res.json())
                    .catch(err=> Observable.throw(err.message));
 } 
 ...
}
 1
Author: Lucas pereira, 2020-06-11 14:45:34

Both a Promiseand an Observable bring abstractions to help handle asynchronous events.

A Promise deals with a single event that can succeed or fail, while a Observable handles 0, 1, or multiple events by firing the specified callback to each of these events.

The biggest advantage of a Observable is to have greater flexibility over a Promise , for for example, you can cancel a request, hold an action, while Promise only has two states that are successful or failed.

A great article related to this topic is: https://tableless.com.br/entendendo-rxjs-observable-com-angular /

 2
Author: ferfabricio, 2019-01-10 02:03:20