Deliver Synchronous Values with the RxJS of() Operator

André Staltz
InstructorAndré Staltz

Share this video with your friends

Send Tweet
Published 7 years ago
Updated a year ago

RxJS is a lot about the so-called "operators". We will learn most of the important operators, one by one. In this lesson, we will see our first creation operator: of().

If you want to deliver synchronous values in the sequence, you use of() instead of writing boilerplate.

[00:00] Now we know the very basics of the observable type. But RXJS is a lot about the so-called 'operators'. If you check the documentation, there are many, many operators available out there. The list is long, but there are actually a reasonable amount of operators that are important to know. That's why this course here exists.

[00:18] We're going to start by looking at the creation operators. These are essentially a static function on the observable type. The observable there has 'of', and 'from', and 'create', etc. We're going to start by looking at 'of'. It's a common pattern to produce a sequence of values, this sequence being synchronous -- we saw like that.

[00:40] Remember, when we had varbar equals our 'x' observable, create the function with observer. Then we delivered observer 'next 42', and then we delivered observer 'next 100', then '200', and then 'complete'.

[00:57] This is a quite common pattern. We just wanted to leave these values and then stop. 'Of' does precisely that. It just allows you to deliver '42', '100', and '200' synchronously, so that is much less much boilerplate to write than the second one here. It does essentially the same, if we now consume this observable by subscribing to it, we get the next value on handler.

[01:32] Here it says, next is 'x'. Then we have an error handler, so on 'error of error', and then it has the completion handler. Here we say, 'done on the console log.'

[01:53] If you run this, we see '42', '100' and '200', and done. That's what 'of' is about. If you want to deliver synchronous values in the sequence, you use 'of' instead of writing this boilerplate.