Raj Saha
Posted on August 6, 2022
Let's say you're in a situation where you're listening to one FormControl
but you're dependent on the value of another FormControl
.
There are two elegant (in my opinion) solutions to this that I've come across.
Solution #1 - use withLatestFrom
withLatestFrom
is an rxjs operator that, as the name suggests, lets you pull the latest value of whatever Observable(s) that you pipe in.
Here I am listening to the stream of field2
but the subscription is executed only when field1
has a value.
Solution #2 - use combineLatestWith
combineLatestWith
is another rxjs operator that combines multiple streams and executes when any one of the Observables emit a value.
Both are useful in different scenarios
Here is what I mean by that -
With withLatestFrom
, the subscription is executed only when field2
undergoes a value change and field1
has a value. So if you just change the value of field1
, nothing happens.
With combineLatestWith
, the subscription is executed when any of the controls undergo value changes. This can be problematic if you're running a lot of code in the subscription execution. So, use it with caution!
The videos below show what I mean.
If you want to try the code for yourself, it's up here on GitHub.
Posted on August 6, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 30, 2024
October 29, 2024