Why does combineLatest runs in this context but forkJoin fails to

Viewed 144

I am digging to rxjs and this seems strange to me, here is an example from the rxjs docs, I tried replacing combineLatest with forkJoin and it doesn't work (The subscriber function isn't called), I believe it should because we already kickstarted the obeservables with startsWith(0)

import { fromEvent, combineLatest, forkJoin } from "rxjs";
import { mapTo, startWith, scan, tap, map } from "rxjs/operators";

// elem refs
const redTotal = document.getElementById("red-total");
const blackTotal = document.getElementById("black-total");
const total = document.getElementById("total");

const addOneClick$ = (id) =>
  fromEvent(document.getElementById(id), "click").pipe(
    // map every click to 1
    mapTo(1),
    // keep a running total
    scan((acc, curr) => acc + curr, 0),
    startWith(0)
  );

combineLatest(addOneClick$("red"), addOneClick$("black")).subscribe(
  ([red, black]) => {
    redTotal.innerHTML = red;
    blackTotal.innerHTML = black;
    total.innerHTML = red + black;
    console.log(red, black);
  }
);
<!DOCTYPE html>
<html>

<head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
</head>

<body>
    <div>
        <button id="red">Red</button>
        <button id="black">Black</button>
    </div>
    <div>Red: <span id="red-total"></span></div>
    <div>Black: <span id="black-total"></span></div>
    <div>Total: <span id="total"></span></div>

    <script src="src/index.js">
    </script>
</body>

</html>

1 Answers

combineLatest() starts emitting once every observable emits one value. forkJoin() starts emitting once every observable is completed. fromEvent() does not send a complete signal, so that is why using forkJoin() doesn't emit anything.

Related