shareReplay.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { ReplaySubject } from '../ReplaySubject';
  2. export function shareReplay(configOrBufferSize, windowTime, scheduler) {
  3. let config;
  4. if (configOrBufferSize && typeof configOrBufferSize === 'object') {
  5. config = configOrBufferSize;
  6. }
  7. else {
  8. config = {
  9. bufferSize: configOrBufferSize,
  10. windowTime,
  11. refCount: false,
  12. scheduler,
  13. };
  14. }
  15. return (source) => source.lift(shareReplayOperator(config));
  16. }
  17. function shareReplayOperator({ bufferSize = Number.POSITIVE_INFINITY, windowTime = Number.POSITIVE_INFINITY, refCount: useRefCount, scheduler, }) {
  18. let subject;
  19. let refCount = 0;
  20. let subscription;
  21. let hasError = false;
  22. let isComplete = false;
  23. return function shareReplayOperation(source) {
  24. refCount++;
  25. let innerSub;
  26. if (!subject || hasError) {
  27. hasError = false;
  28. subject = new ReplaySubject(bufferSize, windowTime, scheduler);
  29. innerSub = subject.subscribe(this);
  30. subscription = source.subscribe({
  31. next(value) {
  32. subject.next(value);
  33. },
  34. error(err) {
  35. hasError = true;
  36. subject.error(err);
  37. },
  38. complete() {
  39. isComplete = true;
  40. subscription = undefined;
  41. subject.complete();
  42. },
  43. });
  44. if (isComplete) {
  45. subscription = undefined;
  46. }
  47. }
  48. else {
  49. innerSub = subject.subscribe(this);
  50. }
  51. this.add(() => {
  52. refCount--;
  53. innerSub.unsubscribe();
  54. innerSub = undefined;
  55. if (subscription && !isComplete && useRefCount && refCount === 0) {
  56. subscription.unsubscribe();
  57. subscription = undefined;
  58. subject = undefined;
  59. }
  60. });
  61. };
  62. }
  63. //# sourceMappingURL=shareReplay.js.map