Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS: what is bufferSize in shareReplay?

Tags:

rxjs

I don't understand what bufferSize parameter means and what does it effect.

What are the differences between the following?

var published = source
    .shareReplay();

var published = source
    .shareReplay(0)

var published = source
    .shareReplay(1);

var published = source
    .shareReplay(10);
like image 319
WHITECOLOR Avatar asked Jan 21 '16 11:01

WHITECOLOR


People also ask

What does ShareReplay () do in angular?

ShareReplay - Angular. You generally want to use shareReplay when you have side-effects or taxing computations that you do not wish to be executed amongst multiple subscribers. It may also be valuable in situations where you know you will have late subscribers to a stream that needs access to previously emitted values.

What does share Replay do?

This operator is a specialization of replay that connects to a source observable and multicasts through a ReplaySubject constructed with the specified arguments. A successfully completed source will stay cached in the shareReplayed observable forever, but an errored source can be retried.


Video Answer


2 Answers

BufferSize :

  • BufferSize means the number of items cached and replayed
  • On subscribe, It will replays a specific number of emissions
  • Items stayed Cached, even after there is no subscribers

Coming to Question :

var published = source
    .shareReplay();

any subscriber to this will get all the items/stream of data emitted by source

var published = source
    .shareReplay(0)

It will cache last emitted value

var published = source
    .shareReplay(1);

It will cache last emitted value, same like above

var published = source
    .shareReplay(10);

It will cache the last 10 items emitted by source.

More Information : I'm going to explain this concept with one example.

 let source$ = interval(1000)
  .pipe(
    take(5),
    shareReplay(3)
  )
source$.subscribe(res => console.log('1st time=>', res))

setTimeout(() => {
  source$.subscribe(res => console.log('2nd time=>', res))
}, 5000)

Note: Here first subscription just mean to start emitting the values. It will emit values five times as I m using take operator to limit the emission interval It will lead to output :

1st time=> 0
1st time=> 1
1st time=> 2
1st time=> 3 
1st time=> 4

Now Just focus on second observable : as we can see the bufferSize value is set to 3, so It will log last three emitted values

2nd time=> 2
2nd time=> 3
2nd time=> 4
like image 95
mabdullahse Avatar answered Oct 22 '22 21:10

mabdullahse


source     --1--2--3--4--5--6--7
subscriber -----------S---------

with source.shareReplay(2) subscriber will get [2, 3, 4, 5,...]

like image 44
WHITECOLOR Avatar answered Oct 22 '22 23:10

WHITECOLOR