How can Observables be designed to exhibit both synchronous and asynchronous behavior?

From: Understanding the Contrasts Between Promises and Observables

In contrast, a Promise consistently operates asynchronously, while an Observable can function in synchronous or asynchronous manners.

This presents the opportunity to manipulate code in a way that allows Observables to exhibit either synchronous or asynchronous behavior as needed.

What is the inherent behavior of an Observable? Is it predominantly synchronous or asynchronous?

How could one implement functionality where Observables switch between synchronous and asynchronous behaviors based on specific requirements?

Answer №1

It all comes down to how the Observable is triggered.

  1. If the initial call is synchronous, the observable will act synchronously.

const { Observable } = rxjs;

const helloWorld$ = new Observable(observer => {
  observer.next('Hello World');
  observer.complete();
});

console.log('Before subscribing helloWorld$');

helloWorld$.subscribe({
  next: console.log,
  complete: () => console.log('helloWorld$ on complete')
});

console.log('After subscribing helloWorld$');
<script src="//cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.3/rxjs.umd.min.js">
</script>

  1. If the initial call is asynchronous, the observable will behave asynchronously.

const { Observable } = rxjs;

const helloEarth$ = new Observable(observer => {
  // simulating an ajax call
  setTimeout(() => {
    observer.next('Hello Earth from a galaxy far, far away...');
    observer.complete();
  }, 1000);
});

console.log('Before subscribing helloEarth$');

helloEarth$.subscribe({
  next: console.log,
  complete: () => console.log('helloEarth$ on complete')
});

console.log('After subscribing helloEarth$');
<script src="//cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.3/rxjs.umd.min.js">
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Uncaught TypeError in Ajax function definition

I encountered an error in my code that says: Uncaught TypeError: Cannot read property 'toLowerCase' of undefined The interesting thing is, when I remove the following part from my source file: delay(function(){ ... }, 1000); the code works ...

Using PHP to display a message box and redirecting to a different webpage

Currently, I am working on developing a login page using PHP. When the user enters an incorrect username/password combination, I display a JavaScript alert box to notify them. However, after clicking the "OK" button on the alert box, I want to redirect t ...

Collaborate on a component used in multiple modules

In my application, there are two modules: employer and landing. I have created a component in the landing module that I want to share with the employer module. To achieve this, I declared the component in the app.module.ts file of the parent module and use ...

I aim to continuously refresh a dynamic canvas line chart with JSON data

Having trouble with my code - the chart isn't updating. I'm new to using canvasJS charts and could use some help. <%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%> <%@ page import=”java ...

Understanding how the context of an Angular2 component interacts within a jQuery timepicker method

Scenario: I am developing a time picker component for Angular 2. I need to pass values from Angular 2 Components to the jQuery timepicker in order to set parameters like minTime and maxTime. Below is the code snippet: export class TimePicker{ @Input() ...

Having trouble with the Three.js OBJ loader in CodePen?

Currently, I am experiencing a challenge with loading an OBJ file on Three.js. Oddly enough, the functionality seems to be working perfectly fine when I deploy the files on my server as demonstrated here: However, when attempting to run it on Codepen, I e ...

Is it possible to limit the items in a TypeScript array to only accept shared IDs with items in another array?

I'm creating an object called ColumnAndColumnSettings with an index signature. The goal is to limit the values of columnSettings so that they only allow objects with IDs that are found in columns. type Column = { colId: string, width?: number, s ...

Error occurs in console when using .getJSON with undefined JSON, but does not happen when using embedded data

Can someone help me understand why I'm getting an 'undefined' response when I use console.log(tooltipValues), but there's no issue with console.log(tooltipJSON). I've noticed that when I embed the data directly in my JS code, ever ...

Incorporating object into main function of VueJS root component

I have integrated VueJS into my HTML template for an application. When a button is clicked, it passes the object of a component to its root in the following manner: <button v-on:click="$root.savePlan(dataObj)"></button> The dataObj is passe ...

What is causing the addListener function in the events class to malfunction?

I am a beginner in the world of node.js and attempting to execute this piece of code: var eventlib= require('events'); var emitter= new eventlib(); eventlib.addListener('MessageEvent', function() { console.log('Registered the ...

Encountering the identical error message while attempting to execute my application: "Uncaught TypeError: this.microservicesModule.register is not a function."

Despite my repeated attempts to run the application, I am consistently encountering the following error message: "UnhandledPromiseRejectionWarning: TypeError: this.microservicesModule.register is not a function at NestApplication.registerModules ...

The process of altering a grid in HTML and adding color to a single square

I am facing a challenge that I can't seem to overcome. I need to create a game using HTML, CSS, and JS. The concept involves a grid where upon entering a number into a text box, a picture of a cartoon character is displayed in a square which turns gre ...

Trouble arises when extending an MUI component due to a TypeScript error indicating a missing 'css' property

We have enhanced the SnackbarContent component by creating our own custom one called MySnackbarContent: export interface MySnackbarContentProps extends Omit<SnackbarContentProps, 'variant'> { variant?: MyCustomVariant; type?: MyCustomTy ...

What is the correct regex expression for validating decimal numbers between 1.0 and 4.5?

I'm having trouble creating an expression to validate numbers between 1.0 to 4.5 accurately. The current expression I'm using is not working as intended: /^[1-4]{0,1}(?:[.]\d{1,2})?$/ The requirement is to only allow values between 1.0 to ...

Removing an item from a table row cannot be completed due to the inability to retrieve the list_body ID necessary for deletion

I have been working on enhancing the delete button function in my table. The id linked to the list_body must be incorporated into the delete function code. I utilized some jquery methods to render the list onto the webpage. //retrieve user list information ...

Issue with template updating when utilizing ui-router and ion-tabs in Ionic framework

CODE http://codepen.io/hawkphil/pen/LEBNVB I have set up two pages (link1 and link2) accessible from a side menu. Each page contains 2 tabs: link1: tab 1.1 and tab 1.2 link2: tab 2.1 and tab 2.2 To organize the tabs, I am utilizing ion-tabs for each p ...

Use ng-repeat to extract information from an array and populate it into a datalist

I've already tried searching for a solution to my issue on Google, but I couldn't find anything that really helped me. I'm looking to create an input field that also functions like a dropdown. This way, I can either type in my own data or se ...

What is the best way to structure time and avoid mentioning the server name?

After struggling for days, I am reaching out for help as I encounter a null error and difficulty changing the time format in my code below. Despite my efforts, this issue seems unsolvable. Error #1 ------------------------------ (node:8844) UnhandledPromi ...

What is the best way to send data from ajax to a django view?

I have a script for ajax that retrieves the public key and sends other details to the Stripe server for payment. However, I am struggling with sending the dynamic value of the price to item_line. fetch("/config/") .then((result) => { return re ...

Modifying the class of an HTML element using JavaScript

Is it possible to dynamically change the class of an HTML element based on a user's selection with a radio button? I am facing an issue where I receive the following error message: "Error: missing ) after argument list Source File: website Line: 1, C ...