Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS combineLatest function can be imported from both rxjs and rxjs/operators, what is the difference between the two?

The combineLatest function can be imported either from rxjs and from rxjs/operators.

When I import it from rxjs/operators (just like I import combineAll I get the following error:

TS2339: Property 'subscribe' does not exist on type 'OperatorFunction<{}, [{}, number, number, number]>'

I used the following code snippet:

import { timer } from "rxjs";
import { combineLatest } from "rxjs/operators";

const timerOne = timer(1000, 2500);
const timerTwo = timer(1500, 2500);
const timerThree = timer(2000, 2500);

//when one timer emits, emit the latest values from each timer as an array
const combined$ = combineLatest(timerOne, timerTwo, timerThree);

combined$.subscribe(
     ([timerValOne, timerValTwo, timerValThree]) => console.log(`Timer One Latest: ${timerValOne}, Two Latest: ${timerValTwo}, Three Latest: ${timerValThree}`)
);

Therefore, I tried to import it from rxjs instead of rxjs/operators :

import { combineLatest } from "rxjs";

And suddenly it worked. Nice, but can anyone explain what the difference is between the two?

like image 310
Wouter van Koppen Avatar asked Dec 17 '22 20:12

Wouter van Koppen


1 Answers

  1. import { combineLatest } from "rxjs";

    This is so-called "Observable creation method". Basically a method that returns an Observable based on the arguments you pass it (just like from() or of()). Since it return an instance of Observable it has the subscribe() method.

  2. import { combineLatest } from "rxjs/operators";

    This is an operator supposed to be used inside an operator chain. It's a method that returns another method that subscribes to the preceding Observable and returns another Observable that processes every value going through on its output.

That's why it gives you the error Property 'subscribe' does not exist on type..... The subscribe() method doesn't exist on a method returned from combineLatest() operator (it returns yet another function).

like image 67
martin Avatar answered May 23 '23 10:05

martin