Solution - Multicast

Subject

Solution

import { Subject } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { map } from 'rxjs/operators';

interface UserResponse {
  data: {
    id: number;
    email: string;
    first_name: string;
    last_name: string;
    avatar: string;
  };
}

const user = ajax
  .getJSON<UserResponse>('https://reqres.in/api/users/2')
  .pipe(map((response) => response.data));

/**
 * Multiple Observers to a cold observable create multiple
 * independent executions of the observerable.
 *
 * Since our cold observable is performing a fetch request
 * if we look at the network tab in the developer tools we
 * will see multiple requests.
 */
// const sub1 = user$.subscribe(console.log);
// const sub2 = user$.subscribe(console.log);

/**
 * Comment out the above code and use a Subject to multicast.
 */
const userSubject = new Subject();
const sub1 = userSubject.subscribe(console.log);
const sub2 = userSubject.subscribe(console.log);

// user.subscribe({
//   next: (user) => userSubject.next(user),
//   error: (e) => userSubject.error(e),
//   complete: () => userSubject.complete()
// });

user.subscribe(userSubject);

Solution - Multicast

Subject

Solution

import { Subject } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { map } from 'rxjs/operators';

interface UserResponse {
  data: {
    id: number;
    email: string;
    first_name: string;
    last_name: string;
    avatar: string;
  };
}

const user = ajax
  .getJSON<UserResponse>('https://reqres.in/api/users/2')
  .pipe(map((response) => response.data));

/**
 * Multiple Observers to a cold observable create multiple
 * independent executions of the observerable.
 *
 * Since our cold observable is performing a fetch request
 * if we look at the network tab in the developer tools we
 * will see multiple requests.
 */
// const sub1 = user$.subscribe(console.log);
// const sub2 = user$.subscribe(console.log);

/**
 * Comment out the above code and use a Subject to multicast.
 */
const userSubject = new Subject();
const sub1 = userSubject.subscribe(console.log);
const sub2 = userSubject.subscribe(console.log);

// user.subscribe({
//   next: (user) => userSubject.next(user),
//   error: (e) => userSubject.error(e),
//   complete: () => userSubject.complete()
// });

user.subscribe(userSubject);

Copyright

Site © by LiveLoveApp, LLC

We Can Help!

Need help with RxJS in your project?

Hire Us