Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS with immutable datastructures?

I'm working through RxJSKoans and I'm seeing a recurring pattern of feeding in array of results, that the subscriber pushes new values onto:

var Rx = require('rx'),
    Subject = Rx.Subject

var result = [];
var s1 = new Subject();
s1.subscribe(result.push.bind(result));
s1.onNext('foo');
result;  // ['foo']

This is clearly an impure function; the result array is mutated by subscribe.

I've seen small-scale projects on Github that make a stab at this using Immutable.js, but none is actively maintained.

Im wondering if there's a widely-adopted immutable implementation pattern, and if not, why?

like image 587
Allyl Isocyanate Avatar asked Aug 28 '16 23:08

Allyl Isocyanate


1 Answers

I wouldn't call it a pattern, but since you can pass everything through a stream you can also pass in any immutable data structure:

const stream$ = Rx.Subject.create();

stream$
  .map(data => data.set('a', data.get('a') + 1))
  .subscribe(data => console.log(data));

stream$.next(Immutable.Map({ a:1 }));
stream$.next(Immutable.Map({ a:2 }));
<script src="https://npmcdn.com/@reactivex/[email protected]/dist/global/Rx.umd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>

Also, there is no reason to have result as an external state. This is what methods like scan are for. This is would I would suggest you do to manage (internal) state:

const stream$ = Rx.Subject.create();

stream$
  .scan((list, val) => list.push(val), Immutable.List())
  .subscribe(data => console.log(data));

stream$.next('foo');
stream$.next('bar');
<script src="https://npmcdn.com/@reactivex/[email protected]/dist/global/Rx.umd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>
like image 146
Sebastian Sebald Avatar answered Sep 18 '22 12:09

Sebastian Sebald