Hi, for you guys who are working with RxJs observable, when you want to get
the values from the observable, this is the most common way we do.
Nothing is wrong with this method; it makes sense because observable can emit many values in a synchronous or asynchronous manner.
Ok now, let’s say you want to get just only one value from the observable.
The first operator in the pipe makes sure after the observable has emitted one value, it will be unsubscribed automatically.
From my experience, we have to do this quite a lot when we want just to get only one value from the observable as you can see you have to subscribe and put your logic in that callback function which is nested. I always expect to see the clean code, and this is not good enough for me.
This is the way I want; a function that we pass observable as an argument and it returns the first value which will be emitted by that observable.
You see await here, as we all know that the observable can emit the value asynchronously. Ok now, let’s implement the getValue function.
This function simply returns the promise that will be resolved when the observable emit the first non-null and non-undefined value.
Note: I use a generic function here as I want to get the correct type of the emitted value.
And that’s all we need, just a small, simple function. I hope this function can improve readability in your code.