LiveLoveApp logo

Solution - RefCount Operator

Solution

import { interval, Subject } from 'rxjs';
import { multicast, refCount } from 'rxjs/operators';

const observable = interval(1000);

/**
 * 1. Create a new Subject.
 */
const subject = new Subject();

/**
 * 2. Use the multicast operator to create a ConnectableObservable,
 *    and use the refCount operator
 */
const multicasted = observable.pipe(multicast(subject), refCount());

/**
 * 3. Subscribe to the multicasted observable and keep a reference
 *    to the Subscription that is reterned.
 */
const subscription = multicasted.subscribe(console.log);
subscription.add(multicasted.subscribe(console.log));

/**
 * 4. After 5000 milliseconds unsubscribe from the multicasted observable.
 */
setTimeout(() => subscription.unsubscribe(), 5000);