1

Code:

const cold = new Observable((observer: Observer<any>) => {
  observer.next(Math.random());
});

const hot = cold.pipe(share());
hot.subscribe(a =>  console.log('a: ' + a));
hot.subscribe(b =>  console.log('b: ' + b));

}

Expected result - a and b has the same value:

// a: 0.17919353301075858

// b: 0.17919353301075858

Actual result - only get value of a in the browser console:

// a: 0.07958207844185083

Any idea?

bearkeeper
  • 13
  • 2
  • Does this answer your question? [Angular2 observable share is not working](https://stackoverflow.com/questions/41440923/angular2-observable-share-is-not-working) – Powkachu Jan 27 '20 at 13:44
  • a hot observable is something keep emit a value like interval or dom event like mouse move and never complete , what I think you just want to replay the last value – Muhammed Albarmavi Jan 27 '20 at 14:23
  • check this https://www.learnrxjs.io/learn-rxjs/subjects/replaysubject – Muhammed Albarmavi Jan 27 '20 at 14:24

2 Answers2

1

You could try shareReplay(1) to replay last value

https://www.learnrxjs.io/learn-rxjs/operators/multicasting/sharereplay

Also, a good article: https://itnext.io/the-magic-of-rxjs-sharing-operators-and-their-differences-3a03d699d255

andriishupta
  • 497
  • 4
  • 8
0

you can use a hot observable like interval with map operator

import { interval } from 'rxjs';
import { map } from 'rxjs/operators';

const source = interval(1000).pipe(map(() => Math.random()));
const subscribe = source.subscribe(val => console.log(val));

Updated

you can use multicast operator and ReplaySubject

const source: any = interval(1000)
  .pipe(
    take(10),
    map(() => Math.random())
  )
  .pipe(multicast(new ReplaySubject()));

source.connect();

source.subscribe(val => console.log(1, val));
source.subscribe(val => console.log(2, val));

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91