Difference between Observable and Promises

Observables and Promises are both used in asynchronous programming in JavaScript, but they have some fundamental differences:

Promises:

  1. Single Value: Promises represent a single value that will be resolved or rejected at some point in the future.
  2. Once Settled: A promise is settled once, meaning it can either be resolved with a value or rejected with a reason for failure.
  3. Static: Promises are static; once created, their state cannot be changed.
  4. No Cancellation: Once a promise is created, it cannot be canceled.

Example of a Promise:

        
            const myPromise = new Promise((resolve, reject) => {
                // Asynchronous operation
                setTimeout(() => {
                  resolve('Operation completed'); // Resolving the promise with a value
                  // reject(new Error('Operation failed')); // Rejecting the promise with an error
                }, 1000);
              });
              
              myPromise.then((result) => {
                console.log(result); // Output: Operation completed
              }).catch((error) => {
                console.error(error); // Output: Error: Operation failed
              });              
        
    

Observables:

  • Multiple Values: Observables represent a stream of values that can be emitted over time.
  • Lazy Execution: They are lazy; they don't execute until someone subscribes to them.
  • Can Emit Errors: Observables can emit multiple values, including errors.
  • Can be Cancelled: They can be canceled by unsubscribing, allowing for cleanup.

Example of an Observable:

        
            import { Observable } from 'rxjs';

            const myObservable = new Observable(observer => {
              let counter = 0;
              const interval = setInterval(() => {
                observer.next(counter++); // Emitting values in an interval
                // if (counter > 5) observer.error('Something went wrong'); // Emitting an error
              }, 1000);
            
              return () => {
                clearInterval(interval); // Cleanup logic on unsubscription
              };
            });
            
            const subscription = myObservable.subscribe(
              value => console.log(value), // Output: 0, 1, 2, 3, 4, 5...
              error => console.error(error), // Output: Something went wrong
              () => console.log('Complete') // Output when the observable completes
            );
            
            // To unsubscribe and stop receiving values
            // subscription.unsubscribe();            
        
    

In essence, Promises deal with a single future value (success or failure), while Observables handle a sequence of values that can arrive asynchronously over time, allowing more flexibility in handling streams of data or events. Observables also offer additional features like cancellation and handling multiple values/errors efficiently.

How To Set Up a Multi-Node Kafka Cluster using KRaft

Setting up a multi-node Kafka cluster using KRaft (Kafka Raft) mode involves several steps. KRaft mode enables Kafka to operate without the need for Apache ZooKeeper, streamlining the architecture and improving management. Here’s a comprehensiv …

read more

Streamline Data Serialization and Versioning with Confluent Schema Registry …

Using Confluent Schema Registry with Kafka can greatly streamline data serialization and versioning in your messaging system. Here's how you can set it up and utilize it effectively: you can leverage Confluent Schema Registry to streamline data seria …

read more