Master RxJs: Short-hand value selector
Although the beauty of RxJs lies in solving problems asynchronously and by writing pipes that describe reactions to changes, sometimes you need to extract a value from a defined Observable and store it in a variable for use in a synchronous procedure.
An example would be preparing variables from various sources before potentially adding them as parameters to an HTTP-request.
Assuming we have a currentPlayer$
that holds the current player data, and we need to post this using another postPlayer()
function, a commonly seen pattern would be something like this:
While this will often get the job done, there’s a couple of problems with this.
First, it’s verbose. It takes quite a lot of code to achieve relatively little, and it’s not very readable for programmers not already familiar with the pattern.
Second, in the case that currentPlayer$
is asynchronous, it will not work correctly. Depending on how the rest of the code looks, there’s a fair chance in this case it would fail silently and simply forward undefined to…