RxJS Functions (Part 5)
defer
defer
Creates an Observable that, on subscribe, calls an Observable factory to make an Observable for each new Observer.
Use Case
Many use cases exist for defer. One of the primary ones is interacting with promises. As an exercise I wanted to come up with a use case outside of promises, or the random number example.
Currently I’m working on a project that will likely be implementing several feature flags. Let’s say we have a feature that displays a timestamp representing how recently the data has been refreshed. Our fictional app has always set that timestamp value once when the app first loads. Now, however, it has been requested that the app refresh its data automatically every 2 seconds. We want to put the feature behind a flag so it can be turned off if things go south. Our app before the flag might look something like this:
Now we put it behind a flag and, with the help of defer
, handle updating the timestamp as well.
If you load this up with some matching HTML, and keep the flag set to ‘true’, the #timestamp
element will update every two seconds with a new time. Change the flag to false, and the timestamp get’s set once only.
And if you wanted to clean things up a bit and make it a bit more ‘functional’:
What’s going on here?
First I stripped out the comments. Then I replaced our big if
block with a ternary. That’s just some easy refactoring, but what is this generateElementModifier
?
After I did the easy refactoring, I abstracted out the ‘replace’ code to its own replaceHtmlWithTimestamp
function. Once I did that I was left with a few lines that were basically taking an element and modifying it either once, or every 2 seconds. So I created a generator function which takes (flag, element, modifierFn)
and returns a new function which, if flag
is true
, calls modifierFn
with element
every 2 seconds. Otherwise, it will only be called once.
What does this do for us?
generateElementModifier
is now a pure function. If we put the same input in, we’ll get the same output out. Every time. This makes it very testable. It is also much more flexible now. Rather than just being able to replace the HTML of an element with a timestamp, our modifierFn
could do anything to the element we want it to.
Thanks for reading. Stay tuned for Part 6, and don’t forget to checkout the previous articles.