Using RXJS to emit additional values based on the incoming observable value

Being new to RxJs 6.0 (or any RxJs version), I find it powerful yet some basic concepts evade me.

I have a scenario where I want to add an additional value to the output stream based on the source stream, but I'm struggling to figure out how to achieve this. It would be great to have a startsWith operator that can accept a method instead of just a static value. Below is some sample code illustrating the situation:

import { startWith, scan, tap, mergeMap, map, concat } from 'rxjs/operators';

interface IData {
  data: number;
  emitExtraVal: boolean;
}

class obsData implements IData {
  constructor(data: number) {
    this.data = data;
    this.emitExtraVal = false;
  }
  public data: number;
  public emitExtraVal: boolean;

}

class extraData implements IData {
  constructor(data: number) {
    this.data = data;
    this.emitExtraVal = true;
  }

  public data: number;
  public emitExtraVal: boolean;
}
const sourceOne = of(new obsData(1),new obsData(2),new obsData(3));

const finalSource = sourceOne.pipe(
  mergeMap((sData) => concat(of(<IData>new extraData(sData.data), of(sData)))
);
const subscribe = finalSource.subscribe(val => console.log('Data:' + val.emitExtraVal));

The goal is to output an instance of extraData with the number in obsData followed by the received obsData from the source. Although not the exact scenario, this example represents what I am aiming for - generating an extra output followed by another, both dependent on a single input source.

This updated depiction of the issue is inspired by comments, but will fail to execute due to incorrect syntax

This leads to the following error message:

You provided 'function (source) { return source.lift.call(concat_1.concat.apply(void 0, [source].concat(observables))); }' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

---Update--- Here is the corrected solution thanks to the feedback. My main hurdle was using concat from rxjs/operators instead of rxjs in the pipe command.

// RxJS v6+
import { of, fromEvent, combineLatest, concat } from 'rxjs';
import { startWith, scan, tap, mergeMap, map } from 'rxjs/operators';

interface IData {
  data: number;
  emitExtraVal: boolean;
}

class obsData implements IData {
  constructor(data: number) {
    this.data = data;
    this.emitExtraVal = false;
  }
  public data: number;
  public emitExtraVal: boolean;

}

class extraData implements IData {
  constructor(data: number) {
    this.data = data;
    this.emitExtraVal = true;
  }

  public data: number;
  public emitExtraVal: boolean;
}
const sourceOne = of(new obsData(1),new obsData(2),new obsData(3));

const finalSource = sourceOne.pipe(
  mergeMap((sData) => concat(of(<IData>new extraData(sData.data), <IData>sData))
);
const subscribe = finalSource.subscribe(val => console.log('Data:' + val.emitExtraVal));

Answer №1

Generate an additional output followed by another output, both linked to a single input source.

In this scenario, the dataItem represents the "single source input" that is converted into an Observable of its elements using the from operator. Subsequently, you can utilize flattening operators (such as mergeMap or concatMap, depending on your needs) to merge all these Observables into a single entity. Refer to the code snippet below for an example:

const { Observable, of, from, concat } = rxjs; // = require("rxjs")
const { mergeMap } = rxjs.operators; // = require("rxjs/operators")

const complexAjaxCall = id => of(`${id}-from-ajax`);

const ids = [1, 2, 3];

from(ids).pipe(
  mergeMap(id => concat(
    complexAjaxCall(id),
    of(id)
  )),
).subscribe(e => console.log(e));
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9bbb1a3ba89ffe7fbe7fb">[email protected]</a>/bundles/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

VS Code fails to provide auto-suggestions for typed attributes in my library

While working on my React application with a component library, I realized that VS Code isn't providing hints for attributes that are typed with my custom types. Below is a simplified version of the code I'm using: import { ProviderApp } from &ap ...

Could it be that the TypeScript definitions for MongoDB are not functioning properly?

Hello everyone, I'm facing an issue with getting MongoDB to work in my Angular 4 project. In my code, I have the db object as a client of the MongoClient class: MongoClient.connect('mongodb://localhost:27017/test', (err, client) => { ...

Retrieve information from an axios fetch call

Having an issue with the response interface when handling data from my server. It seems that response.data.data is empty, but response.data actually contains the data I need. Interestingly, when checking the type of the last data in response.data.data, it ...

Prompt the user to take an action by opening a modal or dialogue box from a dropdown menu

I am looking to implement a functionality where a modal or dialogue will be opened when a user selects an option from a dropdown menu. As the dropdown menu will have multiple options, different dialogues/modals should appear based on the selected option. ...

Having trouble triggering a click event with React testing library?

I am working with a <Select/> component as shown in the image below. https://i.sstatic.net/ko8Y0.png App.tsx import React, { useState, ChangeEvent } from "react"; import MySelect from "./MySelect"; export default function App ...

Encountering challenges with Object-Oriented Programming combined with Typescript: Are you experiencing a

Currently, I'm in the process of building a comprehensive authentication application using the MERN stack entirely in TypeScript. However, I am encountering some issues (specifically type errors) with my userController file. Here is my routes file: i ...

What is the process for inputting a value within single quotation marks?

I'm working with a code snippet that looks like this: for(var j=0; j < this.arr.length; j++) { arr.push({ id: 'j', label: this.arr[j], display: () => this.arr[j] }) } I am curious about ho ...

What is the relationship between Typescript references, builds, and Docker?

I am facing a dilemma with my projectA which utilizes a common package that is also needed by my other Nodejs services. I am unsure of the best approach to package this in a Docker file. Ideally, running tsc build would compile both the project and the dep ...

Accurate function calls with multiple parameters in TypeScript

As a beginner in TypeScript and currently exploring its integration with AngularJS, I am facing a particular issue where the compiler is not detecting an error. In Angular, a resource provider typically includes a get() method that returns an instance of ...

Is it possible to achieve real-time two-way data binding in a reactive form by passing values from one formgroup to another formgroup? If so, how

There are 2 FormGroups named orderForm and parcelForm on a page. The parcelForm is generated dynamically within a FormArray. In the parcelForm, there are FormControls like net_weight and gross_weight, while the OrderForm has FormControls such as total_net_ ...

Is it possible to define a shared function for enums in TypeScript?

I have created an enumeration called VideoCategoryEnum: enum VideoCategoryEnum { knowledge = 0, condition = 1, interview = 2, speech = 3, entertainment = 4, news = 5, advertisement = 6, others = 7, } I am looking to implement a shared met ...

What is the syntax for declaring a state variable as a Set data type in programming?

Struggling to establish a state variable in React using Typescript. Encountering an error when attempting to specify its type as Set. The purpose of this variable is to contain an array of objects. const [blocksList, setBlocksList] = useState<Set>([ ...

An error has occurred in Typescript stating that there is no overload that matches the call for AnyStyledComponent since the update to nextjs

Upgraded to the latest version of nextjs, 13.3.1, and encountered an error in the IDE related to a styled component: Received error TS2769 after the upgrade: No overload matches this call. Overload 1 of 2, '(component: AnyStyledComponent): ThemedSty ...

How to retrieve a variable from an object within an array using AngularJS code

I recently started learning TypeScript and AngularJS, and I've created a new class like the following: [*.ts] export class Test{ test: string; constructor(foo: string){ this.test = foo; } } Now, I want to create multiple in ...

Please provide TypeScript code for a React wrapper function that augments a component's props with two additional functions

During the course of my project, I implemented a function wrapping React component to incorporate undo/redo functionality using keyboard shortcuts Ctrl+Z and Shift+Ctrl+Z. Here is an example: import React from 'react'; interface WithUndoRedoProp ...

Uncover the solution to eliminating webpack warnings associated with incorporating the winston logger by utilizing the ContextReplacementPlugin

When running webpack on a project that includes the winston package, several warnings are generated. This is because webpack automatically includes non-javascript files due to a lazy-loading mechanism in a dependency called logform. The issue arises when ...

What could be causing the mat-radio button in one card to toggle all other cards as well?

Within my home.component.html file, you will find the following code: <div class="grid grid-cols-5 gap-4 pt-10"> <div *ngFor="let card of cards" class=""> <div *ngIf="card==null;then nil else notnil&q ...

Guide on importing videojs-offset library

I am working on a component that utilizes video.js and HLS streaming in Angular. The component code is as follows: import { Component, ElementRef, AfterViewInit, ViewChild, Input, EventEmitter, Output } from '@angular/core'; import ...

"Using RxJS 6 for a countdown timer in an Angular 6 application

Currently, I am working on implementing a countdown timer in Angular 6 using RxJS 6. My goal is to have the ability to subscribe to the results and reset the timer as needed: Here is what I have tried so far: const timer = interval(1000).pipe( take(4) ); ...

Ways to incorporate the use of the useAsync hook within a submit function

After importing useAsync(hook from 'react-async') and attempting to utilize it post form submission for a POST request, a "can't use hooks inside functions" error is encountered due to the rules of hooks. How can this issue be resolved in o ...