Adam Daniels

Adam Daniels

1567480717

ES6 Promises vs. RxJS Observables

ES6 Promises and RxJS Observables are both used to handle async activity in JavaScript. While an Observable can do everything a Promise can, the reverse is not true...

What is a Promise?

A Promise is a more elegant way of handling async activity in JavaScript.

Promises are native to ES6 meaning you can use them with vanilla JavaScript (assuming you are using ES6 version or later).

Example of a Promise:

let promise = new Promise((resolve) => {
 setTimeout(() => {
   resolve("some value")
 }, 1000`)
})

promise.then(value => {
 console.log(value)
})

Output

some value

A Promise works by taking a function with (optionally) two arguments resolve and reject. The passed in function executes some async code and either resolves or rejects.

Once the Promise resolves, its then() method executes a handler function with the emitted value.

This is a very basic example of a Promise. For a more in-depth explanation with examples, check out JavaScript ES6

What is an Observable?

Observables (in the JavaScript context) are the RxJS implementation of the observer design pattern.

Observables are an alternative to Promises for handling async activity:

Example of an Observable:

const { Observable } = require(‘rxjs’);

let observable = new Observable((observer) => {
 setTimeout(() => {
   observer.next(“some value”)
 }, 1000)
})

observable.subscribe(value => {
 console.log(value)
})

Output

some value

Unlike the Promise, Observables aren’t native to JavaScript. This requires us to import the RxJS library:

const { Observable } = require(‘rxjs’);

While you can implement the observer design pattern yourself, the “Observable” in JavaScript usually refers to the RxJS implementation.

Difference Between Observables and Promises:

Single vs Multiple Values:

A Promise emits a single value:

let promise = new Promise((resolve) => {
 resolve(“a”)
 resolve(“b”)
})

promise.then(value => console.log(value))

Output

a

An Observable can emit multiple values:

let observable = new Observable((observer) => {
 observer.next(“a”)
 observer.next(“b”)
})

observable.subscribe(value => {
 console.log(value)
})

Output

a
b

Once a Promise resolves, that’s it. You can’t call resolve twice and get different values. Only the first value a is returned by the promise.

An Observable can emit multiple values. Calling next() executes the handler function each time. Both a and b are returned.

Eager vs Lazy Execution:

A Promise executes the moment it is defined:

let promise = new Promise((resolve) => {
 console.log(“promise is running”)
 resolve(“a”)
})

console.log(“start”)
promise.then(value => console.log(value))
console.log(“end”)

Output

promise is running
start
end
a

An Observable executes only when subscribe() is called:

let observable = new Observable((observer) => {
 console.log(“observable is running”)
 observer.next(“a”)
})

console.log(“start”)
observable.subscribe(value => console.log(value))
console.log(“end”)

Output

start
observable is running
a
end

A Promise executes the moment it’s defined. Even if we don’t call then(), the Promise executes. This is considered eager execution.

An Observable executes only when subscribe() is called. If we don’t call subscribe(), nothing executes. This is considered lazy execution.

Cancellable:

A Promise can’t be canceled. That’s it. No example needed.

An Observable can be canceled via unsubscribe():

let observable = new Observable((observer) => {
 setTimeout(() => {
   console.log(“calling next”)
   observer.next(“a”)
 }, 1000)
})

sub = observable.subscribe(value => console.log(value))
sub.unsubscribe()

Output

calling next

Notice how we use setTimeout() to mimic async activity. By calling unsubscribe() on our subscription, you can effectively cancel an Observable before it executes.

Unicast vs Multicast:

A Promise is unicast meaning you get the same value every time you call the async flow:

let promise = new Promise((resolve) => {
   resolve(Math.random())
})

promise.then(value => console.log(value))
promise.then(value => console.log(value))

Output

0.768598539600432

An Observable is multicast meaning a separate execution occurs for every call to subscribe:

let observable = new Observable((observer) => {
 observer.next(Math.random())
})

observable.subscribe(value => console.log(value))
observable.subscribe(value => console.log(value))

Output

0.6964325798899575
0.5931491554914805

With a Promise we get the same value no matter how many times we call then().

With an Observable we get a different value every time we call subscribe().

Sync vs Async Handlers:

A Promise has async handlers. This means a Promise won’t execute synchronously with the rest of your code:

let promise = new Promise((resolve) => {
   resolve(“promise is resolving”)
})

console.log(“START”)
promise.then(value => console.log(value))
console.log(“END”)

Output

START
END
promise is resolving

An Observable has sync handlers. This means an Observable WILL execute synchronously with the rest of the code:

let observable = new Observable((observer) => {
 observer.next(“next being called”)
})

console.log(“START”)
observable.subscribe(value => console.log(value))
console.log(“END”)

Output

START
next being called
END

Notice how the Promise executes asynchronously from the rest of the code. The code doesn’t wait for the Promise to run.

The Observable executes synchronously with the rest of the code. The code waits for the Observable to emit a value before continuing.

Promise vs RxJS

Remember that the Observable class is from the RxJs library. The RxJS library is the JavaScript implementation of ReactiveX.

ReactiveX is a project for implementing reactive programming across different languages. You can implement Observables in other languages like Java and Ruby as well.

The ReactiveX API also comes with a bunch of operators which are functions that can be applied to observables. Using RxJS, you can apply functions like map() and filter() to values emitted by observables.

The ES6 Promise doesn’t have anything comparable to these operator functions…

Conclusion

Promises and Observables both handle async activity in JavaScript. While the Promise is native to ES6, the RxJS Observable requires the RxJS library.

Observables can do things promises can’t. With observables, you get some extra advantages that can be worth while depending on your use case.

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

The Complete JavaScript Course 2019: Build Real Projects!

The Web Developer Bootcamp

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

ES6 Arrow Functions Cheatsheet

Getting Started with ES6 Arrow Functions in JavaScript

The Complete Guide to ES6 Destructuring

Dropbox API / JavaScript ES6 Tutorial - Expense Organizer

Authenticate a Node ES6 API with JSON Web Tokens

#javascript #es6

What is GEEK

Buddha Community

ES6 Promises vs. RxJS Observables

Promise.allSettled() vs Promise.all()

Promise.allSetlled() is recently introduced in ECMA 2020.
Check out how it is different from Promise.all()

https://www.geekstutorialpoint.com/2020/05/promiseallsettled-vs-promiseall.html

#javascript #promise.all #promise.allsettled #ecma #promise #jquery

Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Adam Daniels

Adam Daniels

1567480717

ES6 Promises vs. RxJS Observables

ES6 Promises and RxJS Observables are both used to handle async activity in JavaScript. While an Observable can do everything a Promise can, the reverse is not true...

What is a Promise?

A Promise is a more elegant way of handling async activity in JavaScript.

Promises are native to ES6 meaning you can use them with vanilla JavaScript (assuming you are using ES6 version or later).

Example of a Promise:

let promise = new Promise((resolve) => {
 setTimeout(() => {
   resolve("some value")
 }, 1000`)
})

promise.then(value => {
 console.log(value)
})

Output

some value

A Promise works by taking a function with (optionally) two arguments resolve and reject. The passed in function executes some async code and either resolves or rejects.

Once the Promise resolves, its then() method executes a handler function with the emitted value.

This is a very basic example of a Promise. For a more in-depth explanation with examples, check out JavaScript ES6

What is an Observable?

Observables (in the JavaScript context) are the RxJS implementation of the observer design pattern.

Observables are an alternative to Promises for handling async activity:

Example of an Observable:

const { Observable } = require(‘rxjs’);

let observable = new Observable((observer) => {
 setTimeout(() => {
   observer.next(“some value”)
 }, 1000)
})

observable.subscribe(value => {
 console.log(value)
})

Output

some value

Unlike the Promise, Observables aren’t native to JavaScript. This requires us to import the RxJS library:

const { Observable } = require(‘rxjs’);

While you can implement the observer design pattern yourself, the “Observable” in JavaScript usually refers to the RxJS implementation.

Difference Between Observables and Promises:

Single vs Multiple Values:

A Promise emits a single value:

let promise = new Promise((resolve) => {
 resolve(“a”)
 resolve(“b”)
})

promise.then(value => console.log(value))

Output

a

An Observable can emit multiple values:

let observable = new Observable((observer) => {
 observer.next(“a”)
 observer.next(“b”)
})

observable.subscribe(value => {
 console.log(value)
})

Output

a
b

Once a Promise resolves, that’s it. You can’t call resolve twice and get different values. Only the first value a is returned by the promise.

An Observable can emit multiple values. Calling next() executes the handler function each time. Both a and b are returned.

Eager vs Lazy Execution:

A Promise executes the moment it is defined:

let promise = new Promise((resolve) => {
 console.log(“promise is running”)
 resolve(“a”)
})

console.log(“start”)
promise.then(value => console.log(value))
console.log(“end”)

Output

promise is running
start
end
a

An Observable executes only when subscribe() is called:

let observable = new Observable((observer) => {
 console.log(“observable is running”)
 observer.next(“a”)
})

console.log(“start”)
observable.subscribe(value => console.log(value))
console.log(“end”)

Output

start
observable is running
a
end

A Promise executes the moment it’s defined. Even if we don’t call then(), the Promise executes. This is considered eager execution.

An Observable executes only when subscribe() is called. If we don’t call subscribe(), nothing executes. This is considered lazy execution.

Cancellable:

A Promise can’t be canceled. That’s it. No example needed.

An Observable can be canceled via unsubscribe():

let observable = new Observable((observer) => {
 setTimeout(() => {
   console.log(“calling next”)
   observer.next(“a”)
 }, 1000)
})

sub = observable.subscribe(value => console.log(value))
sub.unsubscribe()

Output

calling next

Notice how we use setTimeout() to mimic async activity. By calling unsubscribe() on our subscription, you can effectively cancel an Observable before it executes.

Unicast vs Multicast:

A Promise is unicast meaning you get the same value every time you call the async flow:

let promise = new Promise((resolve) => {
   resolve(Math.random())
})

promise.then(value => console.log(value))
promise.then(value => console.log(value))

Output

0.768598539600432

An Observable is multicast meaning a separate execution occurs for every call to subscribe:

let observable = new Observable((observer) => {
 observer.next(Math.random())
})

observable.subscribe(value => console.log(value))
observable.subscribe(value => console.log(value))

Output

0.6964325798899575
0.5931491554914805

With a Promise we get the same value no matter how many times we call then().

With an Observable we get a different value every time we call subscribe().

Sync vs Async Handlers:

A Promise has async handlers. This means a Promise won’t execute synchronously with the rest of your code:

let promise = new Promise((resolve) => {
   resolve(“promise is resolving”)
})

console.log(“START”)
promise.then(value => console.log(value))
console.log(“END”)

Output

START
END
promise is resolving

An Observable has sync handlers. This means an Observable WILL execute synchronously with the rest of the code:

let observable = new Observable((observer) => {
 observer.next(“next being called”)
})

console.log(“START”)
observable.subscribe(value => console.log(value))
console.log(“END”)

Output

START
next being called
END

Notice how the Promise executes asynchronously from the rest of the code. The code doesn’t wait for the Promise to run.

The Observable executes synchronously with the rest of the code. The code waits for the Observable to emit a value before continuing.

Promise vs RxJS

Remember that the Observable class is from the RxJs library. The RxJS library is the JavaScript implementation of ReactiveX.

ReactiveX is a project for implementing reactive programming across different languages. You can implement Observables in other languages like Java and Ruby as well.

The ReactiveX API also comes with a bunch of operators which are functions that can be applied to observables. Using RxJS, you can apply functions like map() and filter() to values emitted by observables.

The ES6 Promise doesn’t have anything comparable to these operator functions…

Conclusion

Promises and Observables both handle async activity in JavaScript. While the Promise is native to ES6, the RxJS Observable requires the RxJS library.

Observables can do things promises can’t. With observables, you get some extra advantages that can be worth while depending on your use case.

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

The Complete JavaScript Course 2019: Build Real Projects!

The Web Developer Bootcamp

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

ES6 Arrow Functions Cheatsheet

Getting Started with ES6 Arrow Functions in JavaScript

The Complete Guide to ES6 Destructuring

Dropbox API / JavaScript ES6 Tutorial - Expense Organizer

Authenticate a Node ES6 API with JSON Web Tokens

#javascript #es6

RxJS Basics in Examples

Let’s take a look at simple examples of using RxJS, and after that, I hope, you will get the basic idea behind it.

What will be covered in this article:

  • 1. Simplest example
  • 2. Observer
  • 3. Observable
  • 4. Subscription
  • 5. RxJS API List: “index” functions:
  • 5.1 concat
  • 5.2 merge
  • 5.3 forkJoin
  • 5.4 fromEvent
  • 5.5 iif
  • 5.6 defer
  • 6. Http requests using “ajax”

#subscription #observer #asynchronous #rxjs #observables

Shawn  Durgan

Shawn Durgan

1603591204

Reactive Programming: Hot Vs. Cold Observables

The Observer Pattern is at the core of reactive programming, and observables come in two flavors: hot and cold. This is not explicit when you are coding, so this article explains how to tell the difference and switch to a hot observable. The focus is on hot observables. The concepts here are relevant to all languages that support reactive programming, but the examples are in C#. It’s critical to understand the distinction before you start doing reactive programming because it will bring you unstuck if you don’t.

Please support this blog by signing up for my course Introduction to Uno Platform.

Reactive Programming

It’s hard to clearly define what Reactive Programming is because it spans so many languages and platforms, and it has overlap with programming constructs like events in C#. I recommend reading through the Wikipedia article because it attempts to give a history of reactive programming and provide objective information.

In a nutshell, reactive programming is about responding to events in the form of sequences (also known as streams) of data. Technically, any programming pattern that deals with this is a form of reactive programming. However, a pattern called the Observer pattern has emerged as the de facto standard for reactive programming. Most programming languages have frameworks for implementing the observer pattern, and the observer pattern has become almost synonymous with reactive programming.

Here are some popular frameworks:

RxJS (JavaScript)

ReactiveUI (.Net)

ReactiveX (Java oriented – with implementations for many platforms)

RxDart (Dart)

The concept is simple. Observables hold information about observers who subscribe to sequences of notifications. The observable is responsible for sending notifications to all of the subscribed observers.

Note: The publish-subscribe (pub/sub pattern) is a closely related pattern, and although technically different, is sometimes used interchangeably with the observer pattern.

Hot Observables

Hot observables start producing notifications independently of subscriptions. Cold observables only produce notifications when there are one or more subscriptions.

Take some time to read up about the observer pattern if you are not familiar. If you start Googling, be prepared for many different interpretations of the meaning. This article explains it well and gives examples in C#. This article is another good article on the topic of hot and cold observables.

A hot observable is simpler because only one process runs to generate the notifications, and this process notifies all the observers. A hot observable can start without any subscribed observers and can continue after the last observer unsubscribes.

On the other hand, a cold observable process generally only starts when a subscription occurs and shuts down when the subscription ends. It can run a process for each subscribed observer. This is for more complex use cases.

#.net #c# #reactive programming #software #.net #dart #hot observable #java #javascript #observable #observer pattern #pubsub #reactive #reactiveui