-
Notifications
You must be signed in to change notification settings - Fork 7
DosAndDonts
Here are some Dos and Don'ts for reactive-state:
When using .watch(), always provide a selector function that picks exactly the properties from the state that you are interested in:
const store = Store.create({
counter: 0,
todos: ["Walk dog", "Learn RxJS"]
});
Do:
const todos = store.watch(state => state.todos);
Don't:
const todos = store.watch().pipe(map(state => state.todos))
Reasoning: .watch()
performs a shallow-equal check on the return value of your selector function (state => state.todos
). That way, only if the todos array changes, a new value will be emitted. By using .watch()
without any arguments, the identity function state => state
is used. The shallow-equal check is still performed, but if for example the counter
property changes, a new value on the todos
observable will be emitted - even though the list of todos did not change!
Often times, you will want to forward values from one observable to a Subject, using .subscribe(subject)
. It is perfectly fine in RxJS to pass an Observer
to .subscribe()
.
But beware: Passing an Observer to .subscribe()
will also forward the complete
and error
event! If your observable completes, the Subject will also complete. And after completion, the Subject cannot ever emit a value again!
Don't (or only do when knowing whats going on)
const action = new Subject();
interval(100).pipe(
take(10),
map(n => n * 2)
).subscribe(action);
Do:
const action = new Subject();
interval(100).pipe(
take(10),
map(n => n * 2)
).subscribe(n => action.next(n))
This way, error and complete events in your source observable will not be forwarded to the action.