Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering a BehaviorSubject

Tags:

rxjs

I have a BehaviorSubject that I'd like to be able to filter, but maintain it's behavior-subject-like quality that new subscribers always get a value when they subscribe, even if the last value emitted was filtered out. Is there a succinct way to do that using built-in functions from rxjs? For example:

const isEven = (n) => n % 2 === 0;
const source = new BehaviorSubject(1);
const stream = source.pipe(filter(isEven));
stream.subscribe((n) => console.log(n)); // <- I want this to print `1`
source.next(2); // prints `2`; that's good
source.next(3); // does not print anything; that's good

I've written my own implementation, but would prefer a simpler solution using existing operators instead if it's easy.

like image 632
Eric Simonton Avatar asked Apr 05 '19 00:04

Eric Simonton


1 Answers

Just use a second BehaviorSubject

const { BehaviorSubject } = rxjs;
const { filter} = rxjs.operators;

const isEven = (n) => n % 2 === 0;
const source = new BehaviorSubject(1);
const stream = new BehaviorSubject(source.getValue());

source.pipe(filter(isEven)).subscribe(stream);

stream.subscribe(val => { console.log(val); });
source.next(2);
source.next(3);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>
like image 96
Adrian Brand Avatar answered Sep 28 '22 00:09

Adrian Brand