Skip to main content

Difference between Observables and Promises


Observables vs Promises

Asynchronous programming in JavaScript can be achieved by using - Callbacks, Promises, async/await, RxJs Observables 

Observables are used to transfer messages between publishers and subscribers in your applications. Observables are a part of RxJs(Reactive extensions for javascript) which is a library for reactive programming using observables.

Angular uses observables for a lot of asynchronous programming and event handling. For example,
  1. For transmitting data between components - EventEmitter extends RxJs Subject and exposes a emit() method to send values to the subscribers.
  2. Angular HTTP Module uses observables to handle AJAX requests and responses - Angular Httpclient returns an observable when making HTTP calls ex. http.get('URL') returns an observable. Few Advantages are the requests can be cancelled through the unsubscribe method, failed requests are retired easily)
  3. The ROUTER and FORMS module use observables to listen and respond to user input events - Router.events, ActivatedRoute, Reactive forms ValueChanges and statuschanges all use observables
  4. AsyncPipe - It uses observables to notify of any changes through the next call           {{ time | async}}

Promises - with promises the executing function returns a promise and you tell the promise what to do when an asynchronous call completes/fails.

Often Observables are preferred over Promise because it provides the features of promise and much more. Let's see the difference between observables and promises.

Promises emit a single value. (Has only two callback functions (resolve and reject)).
Observables emit multiple values over a period of time. (Subscribe method has three callback functions (next, complete, error) next callback if emitted as and when you receive data/values).

A promise handles a single event when an asynchronous operation completes or fails. 
An observable is like a stream and allows to pass zero or more events when the callback is called for each event. It doesn't matter if you want to handle one or multiple events, you can use the same API in each case. 

Promises are not cancellable and the promise will eventually call the success or failed callback even when you don't need the notification or result it provides anymore.
Observables are cancelable and if the result of an expensive async HTTP call isn't needed anymore, the subscription of the observable allows to cancel the subscription.

Promises are eager and are executed immediately.
Observables are not eager and are only executed when subscribed to.

Additionally, Observables provide a lot of powerful operators like map, forEach, filter, reduce, retry, retryWhen etc.









Comments

Popular posts from this blog

How to clear Visual Studio Cache

How to clear visual studio cache Many times, during development you would face situations where project references are not loaded properly or you get missing/error DLL's. This is because the Component cache gets corrupted randomly and without any warnings. The first option that needs to be done is to clear component cache and restart Visual Studio since the Cache might be holding onto previous DLL versions. Here are the steps on how to clear Visual Studio Cache, Clearing Component Cache: Close all Visual Studio Instances running in your machine. Also, make sure devenv.exe is not running in the Task Manager Delete the Component cache directory - %USERPROFILE%\AppData\Local\Microsoft\VisualStudio\1x.0\ComponentModelCache Restart Visual Studio The above steps should fix the cache issue most of the times, but some times that is not enough and you need to perform the below steps as well. Clearing User's Temp Folder: Open the temp folder in this locatio n -  %USERPROFILE%\AppData\Loc...

How to dependency inject to static class

.Net core supports dependency injection. There are many ways that you can inject services like constructor injection, action method injection, property injection. But there will be scenarios where you need to inject dependency services to static classes. For example, injecting services to extension methods. First, create a static class with a one property IServiceProvider type public void ConfigureServices(IServiceCollection services) { services.AddScoped<ILoggerEntry, LoggerEntry>(); services.AddTransient<IMongoRepository, MongoRepository>(); } Second, configure your services in ConfigureServices() method in Startup.cs and define the lifetime of the service instance using either Transient, Scoped or Singleton types. public void ConfigureServices(IServiceCollection services) { services.AddScoped<ILoggerEntry, LoggerEntry>(); services.AddTransient<IMongoRepository, MongoRepository>(); } For the next step to configure the Static class provider proper...

Error NU1605 - Detected package downgrade. Reference the package directly from the project to select a different version.

Error NU1605 - Detected package downgrade This error occurs when a dependency package has a version higher than an existing package version in the project solution. Solution: Add the following in .csproj file < PackageReference > < NoWarn >$( NoWarn ); NU1605 </ NoWarn > </ PackageReference > Another way to do this is to right-click on the solution and  click  Properties . Click  Build  and under  Errors and warnings  add 1605 to the  SuppressWarnings  text box. You can also add multiple error codes that you want to suppress by adding each separated by a comma. P.S. The below screenshot is in VS2019 Mac Version