nikcyber3 nikcyber3
nikcyber3 nikcyber3

Reputation: 43

Rxjs execute and exit the observable on the first match

I have an observable like this. Execution can be checked here.

https://codesandbox.io

import { from, merge , } from 'rxjs';
import { filter, tap, share } from 'rxjs/operators';

const nextTrain$ = 
from(['Yellow', 'Green', 'Neon', 'Amber'])
.pipe(share());

const yellowTrain$ =
  nextTrain$
    .pipe(
      filter(color => color === 'Yellow'),
      tap(() => console.log(`Yellow Color Train is comming`))
    )

const greenTrain$ = nextTrain$
  .pipe(
    filter((color) => color === 'Green'),
    tap(() => console.log(`Green Color Train is comming`))
  )

const blueTrain$ = nextTrain$
  .pipe(
    filter((color) => color === 'Blue'),
    tap(() => console.log(`Blue Color Train is comming`))
  )

merge(yellowTrain$,
  greenTrain$,
  blueTrain$).subscribe();

Currently when I susbscribe to the merge statement what gets printed out is

Yellow Color Train is comming

Green Color Train is comming

Whereas what i want is to print the first matching condition and stop everything else. So that would mean just print

Yellow Color Train is comming.

How do i do this in rxjs ?

Upvotes: 1

Views: 311

Answers (1)

bryan60
bryan60

Reputation: 29355

Just add the first operator:

merge(....).pipe(first())

Upvotes: 2

Related Questions