Combining 2 BehaviorSubjects using ForkJoin

I am facing an issue while trying to use forkJoin with two behavior subject streams in Angular. I expected it to return the values of the two subjects, but it is not working as intended. Is there a way to make this work?

The subscriptions are not being triggered after updating the subjects.

const stream1 = new BehaviorSubject(2);
const stream2 = new BehaviorSubject('two');

Observable.forkJoin(stream1, stream2)
    .subscribe(result => {
         console.log(result);
    });

Answer №1

Consider using combineLatest as an alternative to forkJoin. It can be beneficial if you do not want to wait for a complete() call.

When utilizing combineLatest, whenever any source observable (such as behavior subjects) emits a value, combineLatest will be activated:

const stream1 = new BehaviorSubject(2);
const stream2 = new BehaviorSubject('two');

combineLatest(stream1, stream2)
    .subscribe(r => {
         console.log(r);
    });

stream1.next(3);
stream2.next('three');

Output in the console:

(2) [2, "two"] // initial state

(2) [3, "two"] // triggered by stream1 next

(2) [3, "three"] // triggered by stream2 next

Check out the live demo here: https://stackblitz.com/edit/rxjs-qzxo3n

Answer №2

Take note of the functionality of forkJoin() as described in its documentation:

It waits for Observables to complete and then combines the last values they emitted.

This implies that forkJoin() will emit a value only when all input Observables have completed. When using BehaviorSubject, this requires explicitly calling complete() on both of them:

import { Observable, BehaviorSubject, forkJoin } from 'rxjs';

const stream1 = new BehaviorSubject(2);
const stream2 = new BehaviorSubject('two');

forkJoin(stream1, stream2)
  .subscribe(result => {
    console.log(result);
  });

stream1.complete();
stream2.complete();

Check out the live demo: https://stackblitz.com/edit/rxjs-9nqtx6

Updated for RxJS 6 as of March 2019.

Answer №3

To achieve this, you have the option of using either the take(1) pipe or the complete() method as mentioned previously.

private subjectStream1 = new BehaviorSubject(null);
stream1$: Observable = this.subjectStream1.asObservable();

private subjectStream2 = new BehaviorSubject(null);
stream2$: Observable = this.subjectStream2.asObservable();

forkJoin({
  stream1: this.stream1$.pipe(take(1)),
  stream2: this.stream2$.pipe(take(1))
})
.pipe(takeUntil(this._destroyed$))
.subscribe(values) => console.log(values));

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

Angular-oauth2-oidc does not successfully retrieve the access token when using OAuth2 and SSO

Here's an issue I'm facing: I've been attempting to integrate SSO and OAuth2 flow using angular-oauth2-oidc. When testing with POSTMAN and ThunderClient in VS Code, I managed to receive the correct response (the access_token). However, I am ...

Ensure that the first option in the Woocommerce 2 Variable Product Dropdown List always displays all available choices

I am currently working on a variable WooCommerce product that includes 2 drop-down select fields. The first field is for selecting the Type of Product (framed or unframed artwork) and the second field is for choosing the Size of Artwork. With the help of ...

Switching image source using Firefox add-on

I am venturing into the world of creating my initial browser extension for Firefox. Currently, I am testing it in Firefox Dev v120. I have added an image to the 'images' directory of the extension and have specified "web_accessible_resources" in ...

The Vuex store has not been defined in the vue-router

I'm currently facing an issue with my router setup and a global beforeEach hook that validates authentication. import store from "@/store/store"; const router = new Router({ // routes... }); router.beforeEach((to, from, next) => { if (to ...

Customizing the JavaScript Calendar in Qualtrics

I came across a JavaScript code snippet that allows you to embed a calendar into a Qualtrics question. Specify a date for the survey: <link href="https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css" rel="stylesheet" type="text/css" /> <script sr ...

Utilizing the JSON File in Your HTML Webpage: A Comprehensive Guide

I'm currently trying to integrate the following JSON file into my HTML page. <html> <head> <title> testing get</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> ...

Ways to initiate SVG animations using Angular Component functions?

I am currently working on a project where I want to incorporate an animation that reflects the sorting process of an array of numbers. However, despite successfully sorting the numbers in the array, I am facing challenges with triggering the animations. I ...

Creating an Efficient React Portal Component

Having trouble rendering an input field within a portal. Whenever I change the value of the input, it loses focus. I suspect this is happening due to re-rendering upon state change. Link to code sandbox Any suggestions for a solution? UPDATE Is there a ...

converting an array to JSON format results in a string

I'm attempting to perform an ajax call to a PHP file that will create an array, convert it to JSON, and then display the first item in the array using console.log. Currently, I have this code snippet on my homepage: <script> wi ...

Guide on using PHP to remove the trash icon glyphicon

I am currently creating a data table that includes various actions, one of which is the option to delete a row from both the table and the database. My challenge lies in figuring out how to successfully delete a particular row by simply clicking on the Tr ...

What is the method to assert that two arguments are equal within a function?

When working with TypeScript, you can pass a value to a function and have that function assert the value is true for type narrowing. For example: function assertTrue(v: unknown, message: string): asserts v { if (!v) { throw new MySpecialError(message ...

Trouble with Fetch in JS and PHP not sending parameters

Having trouble getting a PHP function to accept data from JavaScript, despite the PHP class working elsewhere in the application. The getTopFive() function works fine, but data insertion isn't happening as expected. Below is the code snippet along wit ...

Switch back and forth between two different function loops by clicking

I have implemented two sets of functions that animate an SVG: one set runs in a vertical loop (Rightscale.verticalUp and Rightscale.verticalDown) and the other in a horizontal loop (Rightscale.horizontalUp or Rightscale.horizontalDown). On clicking the SVG ...

Retrieving an Element that Triggered an HTTP GET Request in Node.js with Express

In my Express front-end development project, I have a table with rows containing links that trigger GET requests. These requests are sent to the back-end, which is created using node.js, in order to retrieve files corresponding to each row. All links follo ...

Is there a way to modify the CSS or add custom styling within an iframe form?

Currently I am working on the following page: , where an embedded javascript form called infusionsoft (iframe form) needs to be made responsive at the request of my client. I'm wondering if there is a way to override the css or inject custom styles i ...

Incorporate the xml2js JavaScript library with Angular 2 for enhanced functionality

I've been attempting to utilize xml2js as an XML parser within my Angular 2 (RC 1 with TypeScript) web application. Unfortunately, I've encountered several errors without finding a solution that works. Here is the detailed process I followed: ...

Choose the data from the initial entry to the second entry within the database

I am currently working on a project that requires me to retrieve dates from a database. The goal is to replace outdated dates with newer ones as they pass. Unfortunately, I am unsure how to achieve this and would greatly appreciate any assistance. It see ...

Understanding Restangular with Typescript can be challenging, especially when dealing with a 'restangularized' response object

In my project, I am working with Angular 1.5.x using TypeScript in combination with restangular to access a remote API. Here is an overview of the scenario: The API endpoint I am connecting to is http://localhost:53384/api/timezones. Making a GET request ...

Utilize JSON parsing with AngularJS

My current code processes json-formatted text within the javascript code, but I would like to read it from a json file instead. How can I modify my code to achieve this? Specifically, how can I assign the parsed data to the variable $scope.Items? app.co ...

What is the purpose of deserializing the user for every request using PassportJS?

While I have scoured the official documentation and various online resources, I am still unable to find a solution to what seems like an obvious question. When working with Passport.js, it is necessary to define two methods - one for serializing and one f ...