Ways to combine observables with just one observer receiving emitted values

Hello, I have a specific goal in mind with rxjs, but I am facing some challenges trying to achieve it within certain parameters.

Here is what I aim to accomplish:

first$      ---x|
second$         ------x|
subscribe   -----------x|

However, this is the current outcome:

first$      ---x|
second$         ------x|
subscribe   ---x------x

This is the code snippet I am working with:

const checkFirstSide$: Observable<boolean> = this.checkSide('first');
const checkOtherSide$: Observable<boolean> = this.checkSide('other');

concat(
    checkFirstSide$,
    checkOtherSide$
).pipe(
    timeout(15000)
).subscribe({
    next: (success) => {
        doSomething(success);
    },
    error: (error) => {
        handleError(error);
    },
    complete: () => {
        doSomethingOnComplete();
    }
});

The specific constraints are as follows:

  1. Subscriptions need to occur sequentially
  2. Each subscription should only proceed if the previous one was successful (no errors)
  3. All actions must time out after 15 seconds
  4. In case of an error, execution should halt (triggering handleError and completing)
  5. The observer's next function should execute once, followed by complete

Answer №1

Perhaps...

transition to the second observer once the first signal is received.

checkFirstSide$.pipe(
  switchMap(x => checkOtherSide$),
  timeout(15000)
)

or accumulate the data from your observers and emit them together in the end.

concat(
  checkFirstSide$,
  checkOtherSide$
).pipe(
  toArray(),
  timeout(15000)
)

Answer №2

To achieve the desired outcome, I recommend utilizing the forkJoin method. Be sure to refer to the official API documentation for more information!


UPDATE: My apologies for the confusion earlier! It seems that using a pipe along with the switchMap operator will be more suitable in this case:

checkFirstSide$.pipe(
  switchMap(resFirstSide => {
    doSomething(resFirstSide);
    return checkOtherSide$;
  });
).subscribe(resOtherSide => doSomethingOnComplete());

Answer №3

As per my understanding, the option closest to your requirement may be found in the official API reference for concat. However, I am unsure about how it handles scenarios where one observable throws an error.

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

Refining search results with dynamic filter conditions in TypeScript array objects and using search refiners in SharePoint

In my Typescript and SharePoint Search project, I am working on a scenario involving a Collection of Arrays structured as follows: let _SelectedBusinessUnits =[ { "fileName": "XYX.doc", "Region": "APAC", "Country":"Australia;China", "LOB": "Auto;Busines ...

What possible reasons could be preventing communication between nodes in the ej2 DiagramComponent?

Trying to establish a connection between nodes using a datamanager, but encountering an issue when specifying connectionDataSource. The nodes disappear and the screen is left empty, with no errors in the console. @Component({ selector: 'app-relation ...

Tips for changing the color of an MUI 5 checkbox and label when hovering

I am looking to create a checkbox enclosed in a wrapper with a label. The goal is to change the color of everything inside the wrapper when it is hovered over. Here is an example image: https://i.sstatic.net/T3OU5.png Below is the code I have attempted: ...

Establish the predefined date for the air-datepicker

I am currently utilizing the air-datepicker inline feature. My objective is to establish the starting date for it. Below is the script detailing my attempt: export function load_datepickers_inline():void { const search_legs_0_datepicker = $("#search_leg ...

Testing Angular Singleton Service with Unit Tests

I have been tackling a unit test in Angular related to a singleton service. Specifically, I have a UserService that is declared as a singleton in the root module of the application. My goal is to create a unit test that verifies whether the instance of U ...

Employing various Class Methods based on the chosen target compiler option

Is there a way to instruct TypeScript to utilize different implementations of methods within the same class, based on the specified target option in the tsconfig.json file? I am currently transitioning one of my scripts to TypeScript to streamline managem ...

Incorporate a generic type into a React Functional Component

I have developed the following component: import { FC } from "react"; export interface Option<T> { value: T; label: string; } interface TestComponentProps { name: string; options: Option<string>[]; value: string; onChang ...

...might be initialized with an alternative subtype of limitation 'string | number | symbol'

Typescript Playground I developed a function that takes an array of objects and transforms it into an object where the keys represent all the keys from the original objects, paired with arrays of their respective values. Although the functionality is cor ...

Tips for preventing the ngbTypeahead input field from automatically opening when focused until all data is fully mapped

When clicking on the input field, I want the typeahead feature to display the first 5 results. I have created a solution based on the ngbTypeahead documentation. app.component.html <div class="form-group g-0 mb-3"> <input id="typ ...

I encountered an error in my Node.js application stating that it could not find the name 'Userdetailshistory' array. I am puzzled as to why this error is occurring and I suspect it may be due to my

import { Component, OnInit } from '@angular/core'; import { UserdetailshistoryService } from '../../services'; @Component({ selector: 'my-userdetailshistory', templateUrl: './userdetails-history.component.html', ...

Is there a way to import a module generated by typescript using its name directly in JavaScript?

I am trying to bring a function from a typescript-generated module into the global namespace of JavaScript. The typescript module I have is called foo.ts: export const fooFn = (): string => { return "hello"; }; Below is the structure of my HTML file ...

Error with React, key must be unique. What's the issue?

What is causing the issue with unique keys? To resolve the problem, ensure that each list item has a unique key. For example, if we have x_values = {'male':[1,2,3], 'female':[2,3,4]} the keys should be : 'mean-male', ' ...

Is the type safety of Typescript Discriminated Unions failing on nested objects?

I am working on a project using Typescript 4 where I am trying to create an object with discriminated unions. However, it seems that the type safety is not functioning as expected. export enum StageType { PULL = 'pull', FILTER = 'fil ...

Disabling eslint does not prevent errors from occurring for the unicorn/filename-case rule

I have a file called payment-shipping.tsx and eslint is throwing an error Filename is not in camel case. Rename it to 'paymentShipping.tsx' unicorn/filename-case However, the file needs to be in kebab case since it's a next.js page that s ...

Remove the main project from the list of projects to be linted in

Currently in the process of transitioning my Angular application to NX and have successfully created some libraries. I am now looking to execute the nx affected command, such as nx affected:lint, but it is throwing an error: nx run Keira3:lint Oops! Somet ...

An HTML table featuring rows of input boxes that collapse when the default value is not filled in

My table is populated with dynamic rows of input boxes, some of which may have a default value while others return an empty string ''. This causes the table to collapse on those inputs. <tr *ngFor="let d of displayData"> < ...

Highcharts - Customize Pie Chart Colors for Every Slice

I'm working on an angular app that includes highcharts. Specifically, I am dealing with a pie chart where each slice needs to be colored based on a predefined list of colors. The challenge is that the pie chart is limited to 10 slices, and I need to a ...

Function returning promise asynchronously, but caller function failing to resolve the promise

I have been researching similar items without success and I realize that I need a better understanding of promises, but I am facing some challenges. My project involves Ionic 4/Angular 8 with an Azure-based backend. I am trying to display images from Azur ...

Using PrimeNG checkboxes to bind objects in a datatable

PrimeFaces Checkbox In the code snippet below, my goal is to add objects to an array named selectedComponents in a model-driven form when checkboxes are checked. The object type of item1 is CampaignProductModel, which belongs to an array called selectedC ...

Utilizing the WebSocket readyState to showcase the connection status on the application header

I am currently in the process of developing a chat widget with svelte. I aim to indicate whether the websocket is connected or not by utilizing the websocket.readyState property, which has the following values: 0- Connecting, 1- Open, 2- Closing, 3- Close ...