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));