⚠️ This lesson is retired and might contain outdated information.

Map Vue.js Components to Remote Data Streams with RxJS

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 9 months ago

This lesson shows how to map the current tab to a remote stream leveraging the combineLatest operator to grab the latest tab value and the values from loading in a remote data set of people.

Instructor: [00:02] rather than hardcoding our people here, let's delete that and use a people stream instead. I'll create a paper stream, so const people. This will use our create loader function. Going to bring this up above it.

[00:19] Just say create loader and pass in our service, starwars.egghead.training/people. That will load in an array of people. We'll go ahead and return this in our object at the bottom, hit Save, and now we have a whole bunch of tabs with the proper names on them. You'll notice that when I click on them that nothing happens, though.

[00:47] That's because the map that we did before, we tried to map the tab ID to the people tab ID, this people no longer exists. The way we check the array of people off of this stream is by using combine latest people. This essentially means take the active tab and when either of these fires combine the two latest values together and then push that down.

[01:18] The way we're going to do that is with a selector function. The arguments are tab ID and the array of people. The tab ID comes from here, and the array of people comes from here. Then, we'll do a very, very similar look-up where we say people, look up the tab ID and grab their current ID.

[01:38] Hit Save there, and now you see Luke shows up. I'll click on C-3PO, R2-D2, Han Solo, keep on scrolling. Everyone is mapped together properly. This people stream is using this create loader promise. The active tab now combines with that and selects that appropriate ID off of the people array that comes back from the people stream.

[02:05] I don't need so many people for my tab, so I'm going to limit them down to, let's say, people slice. Let's do seven. Now we'll have the first seven results...

Paul Perry
Paul Perry
~ 6 years ago

Hi again everyone! I've got some rxjs 6 updates/fixes for you here:

imports:

import { from, merge, of, combineLatest } from 'rxjs'
import { pluck, map, mapTo, catchError, share, startWith, exhaustMap } from 'rxjs/operators';

and the "luke" function, which I named "getName" below:

const getName$ = combineLatest(
  activeTab$, 
  people$, 
  (tabId, people) => people[tabId].id
)
.pipe( 
  map( id => `https://starwars.egghead.training/people/${id}`),
  exhaustMap( createLoader ),
  catchError(() => of({ name: "Failed :(" }))
).pipe(
  share()
);

As always, if my code doesn't look great, and you know of a better/tidier way to write it, please chip in!

Markdown supported.
Become a member to join the discussionEnroll Today