LiveLoveApp logo

Solution - Connectable

Solution

import { connectable, interval, Observable, Subject } from 'rxjs';

const observable = interval(1000);

/**
 * 1. Use the multicast operator in the pipe of the source observable.
 */
const multicasted = connectable(observable);

/**
 * 2. Subscribe to the multicasted observable and log out the next notification values.
 */
const sub = multicasted.subscribe(console.log);

/**
 * 3. Connect the subject to the source observable.
 */
multicasted.connect();

Bonus

import { connectable, interval, Observable, Subject } from 'rxjs';

const observable = interval(1000);

/**
 * 1. Define a new Subject.
 */
const subject = new Subject<number>();

/**
 * 2. Use the multicast operator in the pipe of the source observable.
 */
const multicasted = connectable(observable, {
  connector: () => subject
});

/**
 * 3. Subscribe to the multicasted observable and log out the next notification values.
 */
const sub = multicasted.subscribe(console.log);

/**
 * 4. Connect the subject to the source observable.
 */
multicasted.connect();