Create a Generic Subscriber in RxJS

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet

Observables never run until you invoke them with subscribe. This also means that the values from the observable don't go anywhere unless you use a subscriber. A basic subscriber is either a function to handle the next value or an object with functions to handle next, complete, and error scenarios.

Instructor: [00:00] Create an observable from an array of one, two, three, four, five. I'll name this, Observable. Then when I subscribe to this, so I'll subscribe here. This will take a function, which can take the value. I will console log out the value.

[00:19] I have a tool running called quokka.js, which is evaluating this while I type. You can see one, two, three, four, and five come out sequentially and that each green block here means that line of code has been called. Instead of passing in a function here, I'm going to pass in an object with the properties of next, which is a function.

[00:41] Before, this is exactly what was called, was a function for next and one called Complete and one called Error. Now you'll see here, this is green. It gets to Complete, and it console logs out undefined, because Complete doesn't take a value. We'll console log out done. Error, this block is white because this never errors out.

[01:06] This object here which we're passing into subscribe can be called a subscriber. We'll assign this object the name of Subscriber. I'll pass that into subscribe. You'll see all the values being logged out as expected.