What is a way to execute a series of requests using rxjs similar to forkJoin and combineLatest, without needing to wait for all requests to finish before viewing the results?

Consider you have a list of web addresses:

urls: string[]

You create a set of requests (in this instance, utilizing Angular's HTTPClient.get which gives back an Observable)

const requests = urls.map((url, index) => this.http.get<Film>(url)

The objective is to run these requests concurrently while receiving responses gradually. In simple terms, if there's something like films$: Observable<Film[]>, I intend for films$ to update step by step with each new response received.

To simulate this scenario, adjust the code snippet above as follows

const requests = urls.map((url, index) => this.http.get<Film>(url).pipe(delay((index + 1)* 1000))

With the updated array of Observables mentioned above, data from each request should be retrieved sequentially since they are not all requested simultaneously. Bear in mind that this is just a representation of staggered data arrival times from individual requests. The requests themselves are executed concurrently.

The aim is to refresh the items in films$ every time any of the requests emit a value.

...

Answer №1

If you're looking for a solution, consider utilizing the scan operator:


const makeRequest = url => this.http.get<Film>(url).pipe(
  catchError(() => EMPTY))
);

films$: Observable<Film[]> = from(urls).pipe(
  mergeMap(url => makeRequest(url)),
  scan((films, film) => films.concat(film), [])
); 

The sequence of actions is as follows:

  • from will emit URLs one by one
  • mergeMap will subscribe to "makeRequest" and emit the result into the stream
  • scan will accumulate results into an array and emit each time a new emission is received

To maintain order, using combineLatest could be beneficial as it emits an array in the same order as the input observables. Each observable can start with startWith(undefined), followed by filtering out the undefined items:


const requests = urls.map(url => this.http.get<Film>(url).pipe(startWith(undefined));

films$: Observable<Film[]> = combineLatest(requests).pipe(
  map(films => films.filter(f => !!f))
); 

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

Unrestricted Angular Audio Playback without CORS Restrictions

I am currently developing a web application using Angular4 that will include the feature of playing audio files. Unfortunately, I am facing an issue where I do not have control over the server serving the media files, and therefore cannot make any modifica ...

Adjusting the Connection header in a jQuery ajax request

I've been attempting to modify the Connection header using the code below, but so far, I haven't had any success jQuery.ajax({ url: URL, async: boolVariable, beforeSend: function(xhr) { xhr.setRequestHeader("Connection ...

Express throwing module errors

I encountered an issue while attempting to expose a REST service in an electron app using expressJS. Following a tutorial, I added express and @types/express to the project. However, when trying to implement a "get" method and running the build with ng bui ...

Press the button to reveal the hidden Side Menu as it gracefully slides out

I'm interested in creating a navigation menu similar to the one on m.facebook.com, but with a unique animated slide-out effect from the left side of the website. Here's the flow I have in mind: Click a button > (Menu is hidden by default) Men ...

A function that takes in a type identifier and a portion of a type, and then outputs the full type

I'm currently facing a challenge with TypeScript generics. I have several types (referred to as Animals) that each have a unique attribute, "type." Additionally, I have a function called createAnimal which takes the type of animal and a partial object ...

I am looking to refund the sum

I need assistance with returning an amount from a specific function. I have created a function called getWalletTotalAmont() getWalletTotalAmont() { let amount = 0; this.http.post<any>(`${this.generalService.apiBaseUrl}api/wallet/getWalletTotal ...

The button event listener in React fails to trigger without a page refresh

Within my index.html file, I have included the following code snippet: <head> ... <script type="text/javascript" src="https://mysrc.com/something.js&collectorId=f8n0soi9" </script> <script ...

Ways to efficiently incorporate data into App.vue from the constructor

My app initialization uses main.js in the following way, import App from './App.vue'; const store = { items: [{ todo: 'Clean Apartment.', },{ todo: 'Mow the lawn!', },{ todo: 'Pick up ...

Problem detected in id modification

My JavaScript function is triggered with an onChange event, which works fine when there's only one. <input class="form-control" type="text" onchange="opert(<?php echo $fetch["id_prod"] ?>,1)" id="name" value="<?php echo $fetch["name_prod" ...

Does jqgrid navgrid have an event called "on Refresh"?

Is there a way to trigger an event before the grid automatically refreshes? I am looking for something similar to "onSearch" but for the reset button. Below is the code snippet for the navgrid: $("#jqGrid").jqGrid('navGrid','#jqGridPag ...

What could be the reason for my code generating the error [$http:badreq]?

I'm currently attempting to retrieve JSON data from a certain URL and am having trouble getting it to work. Despite going through the Angular documentation and other resources, I still can't pinpoint the issue due to my limited experience with An ...

Displaying server errors in an Angular componentIn this tutorial, we

As I work on creating a registration page, my focus has been on posting data to the server. I have successfully implemented client-side and server-side validation mechanisms. Managing client-side errors is straightforward using code such as *ngIf="(emailAd ...

Refresh the dropdown menu selection to the default option

My HTML dropdown menu includes a default option along with dynamically generated options using ng-options. The variable dropdown is bound to the dynamic options, not the default one. <td> <select ng-model="dropdown" ng-options="item as item.n ...

Guidance on using an array to filter an object in Javascript

Looking at the object structure in Chrome Dev Tools, it appears like this: obj: { 1: {...}, 2: {...}, 3: {...}, 4: {...}, 5: {...}, } On the other hand, there is a simple array as well: arr: [1,3,5,7] The goal here is to filter the object bas ...

Utilizing props in makeStyles for React styling

I have a component that looks like this: const MyComponent = (props) => { const classes = useStyles(props); return ( <div className={classes.divBackground} backgroundImageLink={props.product?.image} sx={{ position: "r ...

The term "Highcharts does not exist"

I'm encountering an issue with my code: <html> <head> <title><%=sAtaskaitaTitle%></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name=vs_targetSchem ...

What allows us to create an instance of a generic class even without defining the generic type parameter?

It is intriguing how TypeScript allows the instantiation of a generic class without specifying the actual generic type parameter. For instance, in the code snippet below, the class Foo includes a generic type parameter T. However, when creating a new Foo i ...

Using a static string in Javascript yields no issues, whereas working with variables can sometimes cause problems

I've been struggling with a problem this morning and it's time to ask for help! I have a JavaScript function that takes the value entered by a user into an autocomplete box, uses AJAX to send that value to a PHP script which then queries the data ...

Tips for showing solely the current page number within angular pagination

HTML : <!-- pagination controls --> <div class="pagination-container"> <pagination-controls (pageChange)="onPageChange($event)" [maxSize]="1" [id]="config.id" [directionLinks]="true">< ...

Using Javascript to dynamically add rows to a table, however they mysteriously appear and disappear soon

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserPermisson.aspx.cs" Inherits="TestProjects.UserPermisson" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" ...