Get me outta here!
Showing posts with label rxjs. Show all posts
Showing posts with label rxjs. Show all posts

Monday, March 4, 2024

Reactive Programming

🔎Definition---

JavaScript Promises are objects used to represent the eventual completion (or failure) of an asynchronous operation. They are widely used in modern JavaScript to handle asynchronous tasks in a more readable and manageable way, compared to traditional callback-based approaches. A Promise can be in one of three states:
Pending: Initial state, neither fulfilled nor rejected.
Fulfilled: The operation completed successfully.
Rejected: The operation failed.

On the other hand, RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables. An observable represents a stream of data that can be observed over time. It provides powerful tools for handling asynchronous and event-based programming.

🔩Conversion---

Converting a Promise to an Observable is a common operation in RxJS when integrating with libraries or APIs that return Promises. RxJS provides the from function to convert various data sources, including Promises, into Observables.

Converting an Observable to a Promise is useful when you need to work with Promise-based APIs or when you want to consume Observables in a Promise-based context. RxJS provides the toPromise() operator to convert an Observable into a Promise.

🔚Conclusion---

Promises are simpler and more straightforward for handling single asynchronous operations that produce a single value or error.

Observables are more powerful and suitable for handling multiple asynchronous values over time, supporting cancellation, and offering a wide range of operators for transforming and combining streams of data. When you promise you can't cancel and for cancelling you have to use another library. But you can Unsubscribe to cancel in observables. Also you have to unsubscribe every time that means writing same code couple of times when working on a  big project but in Promises it will go on rejected state.