Create a Generic Subscriber in RxJS

John Lindquist
InstructorJohn Lindquist

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

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.

Tey Taghiyev
Tey Taghiyev
~ 4 years ago

Mandatory ask: Whats the theme you're using

William Kim
William Kim
~ 4 years ago

I have moved this comment to "Flag this lesson for revision". Can I remove this comment? I couldn't find the remove button.

Cliff Smith
Cliff Smith
~ 4 years ago

I can't get this to run - I've got Quokka installed in atom, got all three files in a folder, ran npm install, rxjs is there. import {from} from "rxjs" errors out with 'cannot find module'. Tried all kinds of paths, tried rxjs in the root, tried in a browser with http-server, same issue. What are you doing different...?

Cliff Smith
Cliff Smith
~ 4 years ago

actually, moved to typescript and everything works in Quokka