Difference between Promise and Observable

The main difference between "Promise" and "Observable" is in the nature of the operations they represent.

Promise

- Single Value: Represents a single value that may be available now, in the future, or never.
- Non-Cancelable: Once a "Promise" is resolved or rejected, it cannot be cancelled.
- Error Handling: Uses the ".then()" method to handle success and the ".catch()" method to handle failures.

Promise Example:

const promiseExample = new Promise((resolve, reject) => {
   // simulates an asynchronous operation
   setTimeout(() => {
     const success = true;

     if (success) {
       resolve("The operation was completed successfully!");
     } else {
       reject("The operation failed!");
     }
   }, 2000);
});

promiseExample.then((result) => {
   console.log(result); // success: the operation was completed successfully!
}).catch((error) => {
   console.error(error); // failed: the operation failed!
});

Observable

- Multiple Values Over Time: Can represent a sequence of values emitted over time.
- Cancellable: Can be canceled manually, allowing greater control over the life cycle.
- Event Handling: Uses methods as ".subscribe()" to react to events and manipulate emitted values.

Observable example:

import { Observable, Observer } from 'rxjs';

const observableExample = new Observable((observer: Observer<string>) => {
   // simulates a sequence of values emitted over time
   let count = 0;
   const interval = setInterval(() => {
     observer.next(`Value ${count}`);
     count++;

     if (count > 3) {
       observer.complete(); // indicates that the sequence has been completed
       clearInterval(interval);
     }
   }, 1000);

   // cleanup when canceling subscription
   return () => clearInterval(interval);
});

const subscription = observableExample.subscribe(
   (value) => console.log(value), // handles emitted values
   (error) => console.error(error), // handle errors
   () => console.log('The sequence was completed') // handles sequence completion
);

// unsubscribe after 5 seconds
setTimeout(() => {
   subscription.unsubscribe();
}, 5000);

In summary, while "Promise" is better suited for representing single success or failure operations, "Observable" is more powerful when you are dealing with sequences of events or data over time, as HTTP requests, user events, etc. In many cases in Angular, asynchronous operations are represented as "Observable", especially when they involve continuous data streams.

Nenhum comentário:

Postar um comentário

Internet of Things (IoT) and Embedded Systems

The  Internet of Things (IoT)  and  Embedded Systems  are interconnected technologies that play a pivotal role in modern digital innovation....