Debian Codegraph @

src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableReplay.java

raw
1 /*
2 * Copyright (c) 2016-present, RxJava Contributors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
5 * compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License is
10 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
11 * the License for the specific language governing permissions and limitations under the License.
12 */
13
14 package io.reactivex.rxjava3.internal.operators.observable;
15
16 import java.util.*;
17 import java.util.concurrent.TimeUnit;
18 import java.util.concurrent.atomic.*;
19
20 import io.reactivex.rxjava3.core.*;
21 import io.reactivex.rxjava3.core.Observable;
22 import io.reactivex.rxjava3.core.Observer;
23 import io.reactivex.rxjava3.disposables.Disposable;
24 import io.reactivex.rxjava3.exceptions.Exceptions;
25 import io.reactivex.rxjava3.functions.*;
26 import io.reactivex.rxjava3.internal.disposables.*;
27 import io.reactivex.rxjava3.internal.fuseable.HasUpstreamObservableSource;
28 import io.reactivex.rxjava3.internal.util.*;
29 import io.reactivex.rxjava3.observables.ConnectableObservable;
30 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
31 import io.reactivex.rxjava3.schedulers.Timed;
32
33 public final class ObservableReplay<T> extends ConnectableObservable<T> implements HasUpstreamObservableSource<T> {
34 /** The source observable. */
35 final ObservableSource<T> source;
36 /** Holds the current subscriber that is, will be or just was subscribed to the source observable. */
37 final AtomicReference<ReplayObserver<T>> current;
38 /** A factory that creates the appropriate buffer for the ReplayObserver. */
39 final BufferSupplier<T> bufferFactory;
40
41 final ObservableSource<T> onSubscribe;
42
43 interface BufferSupplier<T> {
44 ReplayBuffer<T> call();
45 }
46
47 @SuppressWarnings("rawtypes")
48 static final BufferSupplier DEFAULT_UNBOUNDED_FACTORY = new UnBoundedFactory();
49
50 /**
51 * Given a connectable observable factory, it multicasts over the generated
52 * ConnectableObservable via a selector function.
53 * @param <U> the value type of the ConnectableObservable
54 * @param <R> the result value type
55 * @param connectableFactory the factory that returns a ConnectableObservable for each individual subscriber
56 * @param selector the function that receives an Observable and should return another Observable that will be subscribed to
57 * @return the new Observable instance
58 */
59 public static <U, R> Observable<R> multicastSelector(
60 final Supplier<? extends ConnectableObservable<U>> connectableFactory,
61 final Function<? super Observable<U>, ? extends ObservableSource<R>> selector) {
62 return RxJavaPlugins.onAssembly(new MulticastReplay<>(connectableFactory, selector));
63 }
64
65 /**
66 * Creates a replaying ConnectableObservable with an unbounded buffer.
67 * @param <T> the value type
68 * @param source the source observable
69 * @return the new ConnectableObservable instance
70 */
71 @SuppressWarnings("unchecked")
72 public static <T> ConnectableObservable<T> createFrom(ObservableSource<? extends T> source) {
73 return create(source, DEFAULT_UNBOUNDED_FACTORY);
74 }
75
76 /**
77 * Creates a replaying ConnectableObservable with a size bound buffer.
78 * @param <T> the value type
79 * @param source the source ObservableSource to use
80 * @param bufferSize the maximum number of elements to hold
81 * @param eagerTruncate if true, the head reference is refreshed to avoid unwanted item retention
82 * @return the new ConnectableObservable instance
83 */
84 public static <T> ConnectableObservable<T> create(ObservableSource<T> source,
85 final int bufferSize, boolean eagerTruncate) {
86 if (bufferSize == Integer.MAX_VALUE) {
87 return createFrom(source);
88 }
89 return create(source, new ReplayBufferSupplier<>(bufferSize, eagerTruncate));
90 }
91
92 /**
93 * Creates a replaying ConnectableObservable with a time bound buffer.
94 * @param <T> the value type
95 * @param source the source ObservableSource to use
96 * @param maxAge the maximum age of entries
97 * @param unit the unit of measure of the age amount
98 * @param scheduler the target scheduler providing the current time
99 * @param eagerTruncate if true, the head reference is refreshed to avoid unwanted item retention
100 * @return the new ConnectableObservable instance
101 */
102 public static <T> ConnectableObservable<T> create(ObservableSource<T> source,
103 long maxAge, TimeUnit unit, Scheduler scheduler, boolean eagerTruncate) {
104 return create(source, maxAge, unit, scheduler, Integer.MAX_VALUE, eagerTruncate);
105 }
106
107 /**
108 * Creates a replaying ConnectableObservable with a size and time bound buffer.
109 * @param <T> the value type
110 * @param source the source ObservableSource to use
111 * @param maxAge the maximum age of entries
112 * @param unit the unit of measure of the age amount
113 * @param scheduler the target scheduler providing the current time
114 * @param bufferSize the maximum number of elements to hold
115 * @param eagerTruncate if true, the head reference is refreshed to avoid unwanted item retention
116 * @return the new ConnectableObservable instance
117 */
118 public static <T> ConnectableObservable<T> create(ObservableSource<T> source,
119 final long maxAge, final TimeUnit unit, final Scheduler scheduler, final int bufferSize, boolean eagerTruncate) {
120 return create(source, new ScheduledReplaySupplier<>(bufferSize, maxAge, unit, scheduler, eagerTruncate));
121 }
122
123 /**
124 * Creates a OperatorReplay instance to replay values of the given source observable.
125 * @param <T> the value type
126 * @param source the source observable
127 * @param bufferFactory the factory to instantiate the appropriate buffer when the observable becomes active
128 * @return the connectable observable
129 */
130 static <T> ConnectableObservable<T> create(ObservableSource<T> source,
131 final BufferSupplier<T> bufferFactory) {
132 // the current connection to source needs to be shared between the operator and its onSubscribe call
133 final AtomicReference<ReplayObserver<T>> curr = new AtomicReference<>();
134 ObservableSource<T> onSubscribe = new ReplaySource<>(curr, bufferFactory);
135 return RxJavaPlugins.onAssembly(new ObservableReplay<>(onSubscribe, source, curr, bufferFactory));
136 }
137
138 private ObservableReplay(ObservableSource<T> onSubscribe, ObservableSource<T> source,
139 final AtomicReference<ReplayObserver<T>> current,
140 final BufferSupplier<T> bufferFactory) {
141 this.onSubscribe = onSubscribe;
142 this.source = source;
143 this.current = current;
144 this.bufferFactory = bufferFactory;
145 }
146
147 @Override
148 public ObservableSource<T> source() {
149 return source;
150 }
151
152 @Override
153 public void reset() {
154 ReplayObserver<T> conn = current.get();
155 if (conn != null && conn.isDisposed()) {
156 current.compareAndSet(conn, null);
157 }
158 }
159
160 @Override
161 protected void subscribeActual(Observer<? super T> observer) {
162 onSubscribe.subscribe(observer);
163 }
164
165 @Override
166 public void connect(Consumer<? super Disposable> connection) {
167 boolean doConnect;
168 ReplayObserver<T> ps;
169 // we loop because concurrent connect/disconnect and termination may change the state
170 for (;;) {
171 // retrieve the current subscriber-to-source instance
172 ps = current.get();
173 // if there is none yet or the current has been disposed
174 if (ps == null || ps.isDisposed()) {
175 // create a new subscriber-to-source
176 ReplayBuffer<T> buf = bufferFactory.call();
177
178 ReplayObserver<T> u = new ReplayObserver<>(buf, current);
179 // try setting it as the current subscriber-to-source
180 if (!current.compareAndSet(ps, u)) {
181 // did not work, perhaps a new subscriber arrived
182 // and created a new subscriber-to-source as well, retry
183 continue;
184 }
185 ps = u;
186 }
187 // if connect() was called concurrently, only one of them should actually
188 // connect to the source
189 doConnect = !ps.shouldConnect.get() && ps.shouldConnect.compareAndSet(false, true);
190 break; // NOPMD
191 }
192 /*
193 * Notify the callback that we have a (new) connection which it can dispose
194 * but since ps is unique to a connection, multiple calls to connect() will return the
195 * same Disposable and even if there was a connect-disconnect-connect pair, the older
196 * references won't disconnect the newer connection.
197 * Synchronous source consumers have the opportunity to disconnect via dispose() on the
198 * Disposable as subscribe() may never return in its own.
199 *
200 * Note however, that asynchronously disconnecting a running source might leave
201 * child observers without any terminal event; ReplaySubject does not have this
202 * issue because the dispose() call was always triggered by the child observers
203 * themselves.
204 */
205
206 try {
207 connection.accept(ps);
208 } catch (Throwable ex) {
209 Exceptions.throwIfFatal(ex);
210 if (doConnect) {
211 ps.shouldConnect.compareAndSet(true, false);
212 }
213 Exceptions.throwIfFatal(ex);
214 throw ExceptionHelper.wrapOrThrow(ex);
215 }
216 if (doConnect) {
217 source.subscribe(ps);
218 }
219 }
220
221 @SuppressWarnings("rawtypes")
222 static final class ReplayObserver<T>
223 extends AtomicReference<Disposable>
224 implements Observer<T>, Disposable {
225 private static final long serialVersionUID = -533785617179540163L;
226 /** Holds notifications from upstream. */
227 final ReplayBuffer<T> buffer;
228 /** Indicates this Observer received a terminal event. */
229 boolean done;
230
231 /** Indicates an empty array of inner observers. */
232 static final InnerDisposable[] EMPTY = new InnerDisposable[0];
233 /** Indicates a terminated ReplayObserver. */
234 static final InnerDisposable[] TERMINATED = new InnerDisposable[0];
235
236 /** Tracks the subscribed observers. */
237 final AtomicReference<InnerDisposable[]> observers;
238 /**
239 * Atomically changed from false to true by connect to make sure the
240 * connection is only performed by one thread.
241 */
242 final AtomicBoolean shouldConnect;
243
244 /** The current connection. */
245 final AtomicReference<ReplayObserver<T>> current;
246
247 ReplayObserver(ReplayBuffer<T> buffer, AtomicReference<ReplayObserver<T>> current) {
248 this.buffer = buffer;
249 this.current = current;
250
251 this.observers = new AtomicReference<>(EMPTY);
252 this.shouldConnect = new AtomicBoolean();
253 }
254
255 @Override
256 public boolean isDisposed() {
257 return observers.get() == TERMINATED;
258 }
259
260 @Override
261 public void dispose() {
262 observers.set(TERMINATED);
263 current.compareAndSet(ReplayObserver.this, null);
264 // we don't care if it fails because it means the current has
265 // been replaced in the meantime
266 DisposableHelper.dispose(this);
267 }
268
269 /**
270 * Atomically try adding a new InnerDisposable to this Observer or return false if this
271 * Observer was terminated.
272 * @param producer the producer to add
273 * @return true if succeeded, false otherwise
274 */
275 boolean add(InnerDisposable<T> producer) {
276 // the state can change so we do a CAS loop to achieve atomicity
277 for (;;) {
278 // get the current producer array
279 InnerDisposable[] c = observers.get();
280 // if this subscriber-to-source reached a terminal state by receiving
281 // an onError or onComplete, just refuse to add the new producer
282 if (c == TERMINATED) {
283 return false;
284 }
285 // we perform a copy-on-write logic
286 int len = c.length;
287 InnerDisposable[] u = new InnerDisposable[len + 1];
288 System.arraycopy(c, 0, u, 0, len);
289 u[len] = producer;
290 // try setting the observers array
291 if (observers.compareAndSet(c, u)) {
292 return true;
293 }
294 // if failed, some other operation succeeded (another add, remove or termination)
295 // so retry
296 }
297 }
298
299 /**
300 * Atomically removes the given InnerDisposable from the observers array.
301 * @param producer the producer to remove
302 */
303 void remove(InnerDisposable<T> producer) {
304 // the state can change so we do a CAS loop to achieve atomicity
305 for (;;) {
306 // let's read the current observers array
307 InnerDisposable[] c = observers.get();
308
309 int len = c.length;
310 // if it is either empty or terminated, there is nothing to remove so we quit
311 if (len == 0) {
312 return;
313 }
314 // let's find the supplied producer in the array
315 // although this is O(n), we don't expect too many child observers in general
316 int j = -1;
317 for (int i = 0; i < len; i++) {
318 if (c[i].equals(producer)) {
319 j = i;
320 break;
321 }
322 }
323 // we didn't find it so just quit
324 if (j < 0) {
325 return;
326 }
327 // we do copy-on-write logic here
328 InnerDisposable[] u;
329 // we don't create a new empty array if producer was the single inhabitant
330 // but rather reuse an empty array
331 if (len == 1) {
332 u = EMPTY;
333 } else {
334 // otherwise, create a new array one less in size
335 u = new InnerDisposable[len - 1];
336 // copy elements being before the given producer
337 System.arraycopy(c, 0, u, 0, j);
338 // copy elements being after the given producer
339 System.arraycopy(c, j + 1, u, j, len - j - 1);
340 }
341 // try setting this new array as
342 if (observers.compareAndSet(c, u)) {
343 return;
344 }
345 // if we failed, it means something else happened
346 // (a concurrent add/remove or termination), we need to retry
347 }
348 }
349
350 @Override
351 public void onSubscribe(Disposable p) {
352 if (DisposableHelper.setOnce(this, p)) {
353 replay();
354 }
355 }
356
357 @Override
358 public void onNext(T t) {
359 if (!done) {
360 buffer.next(t);
361 replay();
362 }
363 }
364
365 @Override
366 public void onError(Throwable e) {
367 // The observer front is accessed serially as required by spec so
368 // no need to CAS in the terminal value
369 if (!done) {
370 done = true;
371 buffer.error(e);
372 replayFinal();
373 } else {
374 RxJavaPlugins.onError(e);
375 }
376 }
377
378 @Override
379 public void onComplete() {
380 // The observer front is accessed serially as required by spec so
381 // no need to CAS in the terminal value
382 if (!done) {
383 done = true;
384 buffer.complete();
385 replayFinal();
386 }
387 }
388
389 /**
390 * Tries to replay the buffer contents to all known observers.
391 */
392 void replay() {
393 @SuppressWarnings("unchecked")
394 InnerDisposable<T>[] a = observers.get();
395 for (InnerDisposable<T> rp : a) {
396 buffer.replay(rp);
397 }
398 }
399
400 /**
401 * Tries to replay the buffer contents to all known observers.
402 */
403 void replayFinal() {
404 @SuppressWarnings("unchecked")
405 InnerDisposable<T>[] a = observers.getAndSet(TERMINATED);
406 for (InnerDisposable<T> rp : a) {
407 buffer.replay(rp);
408 }
409 }
410 }
411 /**
412 * A Disposable that manages the disposed state of a
413 * child Observer in thread-safe manner.
414 * @param <T> the value type
415 */
416 static final class InnerDisposable<T>
417 extends AtomicInteger
418 implements Disposable {
419 private static final long serialVersionUID = 2728361546769921047L;
420 /**
421 * The parent subscriber-to-source used to allow removing the child in case of
422 * child dispose() call.
423 */
424 final ReplayObserver<T> parent;
425 /** The actual child subscriber. */
426 final Observer<? super T> child;
427 /**
428 * Holds an object that represents the current location in the buffer.
429 * Guarded by the emitter loop.
430 */
431 Object index;
432
433 volatile boolean cancelled;
434
435 InnerDisposable(ReplayObserver<T> parent, Observer<? super T> child) {
436 this.parent = parent;
437 this.child = child;
438 }
439
440 @Override
441 public boolean isDisposed() {
442 return cancelled;
443 }
444
445 @Override
446 public void dispose() {
447 if (!cancelled) {
448 cancelled = true;
449 // remove this from the parent
450 parent.remove(this);
451 // make sure the last known node is not retained
452 index = null;
453 }
454 }
455 /**
456 * Convenience method to auto-cast the index object.
457 * @param <U> type index to be casted to
458 * @return the index Object or null
459 */
460 @SuppressWarnings("unchecked")
461 <U> U index() {
462 return (U)index;
463 }
464 }
465 /**
466 * The interface for interacting with various buffering logic.
467 *
468 * @param <T> the value type
469 */
470 interface ReplayBuffer<T> {
471 /**
472 * Adds a regular value to the buffer.
473 * @param value the value to be stored in the buffer
474 */
475 void next(T value);
476 /**
477 * Adds a terminal exception to the buffer.
478 * @param e the error to be stored in the buffer
479 */
480 void error(Throwable e);
481 /**
482 * Adds a completion event to the buffer.
483 */
484 void complete();
485 /**
486 * Tries to replay the buffered values to the
487 * subscriber inside the output if there
488 * is new value and requests available at the
489 * same time.
490 * @param output the receiver of the buffered events
491 */
492 void replay(InnerDisposable<T> output);
493 }
494
495 /**
496 * Holds an unbounded list of events.
497 *
498 * @param <T> the value type
499 */
500 static final class UnboundedReplayBuffer<T> extends ArrayList<Object> implements ReplayBuffer<T> {
501
502 private static final long serialVersionUID = 7063189396499112664L;
503 /** The total number of events in the buffer. */
504 volatile int size;
505
506 UnboundedReplayBuffer(int capacityHint) {
507 super(capacityHint);
508 }
509
510 @Override
511 public void next(T value) {
512 add(NotificationLite.next(value));
513 size++;
514 }
515
516 @Override
517 public void error(Throwable e) {
518 add(NotificationLite.error(e));
519 size++;
520 }
521
522 @Override
523 public void complete() {
524 add(NotificationLite.complete());
525 size++;
526 }
527
528 @Override
529 public void replay(InnerDisposable<T> output) {
530 if (output.getAndIncrement() != 0) {
531 return;
532 }
533
534 final Observer<? super T> child = output.child;
535
536 int missed = 1;
537
538 for (;;) {
539 if (output.isDisposed()) {
540 return;
541 }
542 int sourceIndex = size;
543
544 Integer destinationIndexObject = output.index();
545 int destinationIndex = destinationIndexObject != null ? destinationIndexObject : 0;
546
547 while (destinationIndex < sourceIndex) {
548 Object o = get(destinationIndex);
549 if (NotificationLite.accept(o, child)) {
550 return;
551 }
552 if (output.isDisposed()) {
553 return;
554 }
555 destinationIndex++;
556 }
557
558 output.index = destinationIndex;
559 missed = output.addAndGet(-missed);
560 if (missed == 0) {
561 break;
562 }
563 }
564 }
565 }
566
567 /**
568 * Represents a node in a bounded replay buffer's linked list.
569 */
570 static final class Node extends AtomicReference<Node> {
571
572 private static final long serialVersionUID = 245354315435971818L;
573 final Object value;
574 Node(Object value) {
575 this.value = value;
576 }
577 }
578
579 /**
580 * Base class for bounded buffering with options to specify an
581 * enter and leave transforms and custom truncation behavior.
582 *
583 * @param <T> the value type
584 */
585 abstract static class BoundedReplayBuffer<T> extends AtomicReference<Node> implements ReplayBuffer<T> {
586
587 private static final long serialVersionUID = 2346567790059478686L;
588
589 Node tail;
590 int size;
591
592 final boolean eagerTruncate;
593
594 BoundedReplayBuffer(boolean eagerTruncate) {
595 this.eagerTruncate = eagerTruncate;
596 Node n = new Node(null);
597 tail = n;
598 set(n);
599 }
600
601 /**
602 * Add a new node to the linked list.
603 * @param n the Node instance to add as last
604 */
605 final void addLast(Node n) {
606 tail.set(n);
607 tail = n;
608 size++;
609 }
610 /**
611 * Remove the first node from the linked list.
612 */
613 final void removeFirst() {
614 Node head = get();
615 Node next = head.get();
616 size--;
617 // can't just move the head because it would retain the very first value
618 // can't null out the head's value because of late replayers would see null
619 setFirst(next);
620 }
621
622 final void trimHead() {
623 Node head = get();
624 if (head.value != null) {
625 Node n = new Node(null);
626 n.lazySet(head.get());
627 set(n);
628 }
629 }
630
631 /* test */ final void removeSome(int n) {
632 Node head = get();
633 while (n > 0) {
634 head = head.get();
635 n--;
636 size--;
637 }
638
639 setFirst(head);
640 // correct the tail if all items have been removed
641 head = get();
642 if (head.get() == null) {
643 tail = head;
644 }
645 }
646 /**
647 * Arranges the given node is the new head from now on.
648 * @param n the Node instance to set as first
649 */
650 final void setFirst(Node n) {
651 if (eagerTruncate) {
652 Node m = new Node(null);
653 m.lazySet(n.get());
654 n = m;
655 }
656 set(n);
657 }
658
659 @Override
660 public final void next(T value) {
661 Object o = enterTransform(NotificationLite.next(value));
662 Node n = new Node(o);
663 addLast(n);
664 truncate();
665 }
666
667 @Override
668 public final void error(Throwable e) {
669 Object o = enterTransform(NotificationLite.error(e));
670 Node n = new Node(o);
671 addLast(n);
672 truncateFinal();
673 }
674
675 @Override
676 public final void complete() {
677 Object o = enterTransform(NotificationLite.complete());
678 Node n = new Node(o);
679 addLast(n);
680 truncateFinal();
681 }
682
683 @Override
684 public final void replay(InnerDisposable<T> output) {
685 if (output.getAndIncrement() != 0) {
686 return;
687 }
688
689 int missed = 1;
690
691 for (;;) {
692 Node node = output.index();
693 if (node == null) {
694 node = getHead();
695 output.index = node;
696 }
697
698 for (;;) {
699 if (output.isDisposed()) {
700 output.index = null;
701 return;
702 }
703
704 Node v = node.get();
705 if (v != null) {
706 Object o = leaveTransform(v.value);
707 if (NotificationLite.accept(o, output.child)) {
708 output.index = null;
709 return;
710 }
711 node = v;
712 } else {
713 break;
714 }
715 }
716
717 output.index = node;
718
719 missed = output.addAndGet(-missed);
720 if (missed == 0) {
721 break;
722 }
723 }
724
725 }
726
727 /**
728 * Override this to wrap the NotificationLite object into a
729 * container to be used later by truncate.
730 * @param value the value to transform into the internal representation
731 * @return the transformed value
732 */
733 Object enterTransform(Object value) {
734 return value;
735 }
736 /**
737 * Override this to unwrap the transformed value into a
738 * NotificationLite object.
739 * @param value the value in the internal representation to transform
740 * @return the transformed value
741 */
742 Object leaveTransform(Object value) {
743 return value;
744 }
745 /**
746 * Override this method to truncate a non-terminated buffer
747 * based on its current properties.
748 */
749 abstract void truncate();
750
751 /**
752 * Override this method to truncate a terminated buffer
753 * based on its properties (i.e., truncate but the very last node).
754 */
755 void truncateFinal() {
756 trimHead();
757 }
758 /* test */ final void collect(Collection<? super T> output) {
759 Node n = getHead();
760 for (;;) {
761 Node next = n.get();
762 if (next != null) {
763 Object o = next.value;
764 Object v = leaveTransform(o);
765 if (NotificationLite.isComplete(v) || NotificationLite.isError(v)) {
766 break;
767 }
768 output.add(NotificationLite.<T>getValue(v));
769 n = next;
770 } else {
771 break;
772 }
773 }
774 }
775 /* test */ boolean hasError() {
776 return tail.value != null && NotificationLite.isError(leaveTransform(tail.value));
777 }
778 /* test */ boolean hasCompleted() {
779 return tail.value != null && NotificationLite.isComplete(leaveTransform(tail.value));
780 }
781
782 Node getHead() {
783 return get();
784 }
785 }
786
787 /**
788 * A bounded replay buffer implementation with size limit only.
789 *
790 * @param <T> the value type
791 */
792 static final class SizeBoundReplayBuffer<T> extends BoundedReplayBuffer<T> {
793
794 private static final long serialVersionUID = -5898283885385201806L;
795
796 final int limit;
797
798 SizeBoundReplayBuffer(int limit, boolean eagerTruncate) {
799 super(eagerTruncate);
800 this.limit = limit;
801 }
802
803 @Override
804 void truncate() {
805 // overflow can be at most one element
806 if (size > limit) {
807 removeFirst();
808 }
809 }
810
811 // no need for final truncation because values are truncated one by one
812 }
813
814 /**
815 * Size and time bound replay buffer.
816 *
817 * @param <T> the buffered value type
818 */
819 static final class SizeAndTimeBoundReplayBuffer<T> extends BoundedReplayBuffer<T> {
820
821 private static final long serialVersionUID = 3457957419649567404L;
822 final Scheduler scheduler;
823 final long maxAge;
824 final TimeUnit unit;
825 final int limit;
826 SizeAndTimeBoundReplayBuffer(int limit, long maxAge, TimeUnit unit, Scheduler scheduler, boolean eagerTruncate) {
827 super(eagerTruncate);
828 this.scheduler = scheduler;
829 this.limit = limit;
830 this.maxAge = maxAge;
831 this.unit = unit;
832 }
833
834 @Override
835 Object enterTransform(Object value) {
836 return new Timed<>(value, scheduler.now(unit), unit);
837 }
838
839 @Override
840 Object leaveTransform(Object value) {
841 return ((Timed<?>)value).value();
842 }
843
844 @Override
845 void truncate() {
846 long timeLimit = scheduler.now(unit) - maxAge;
847
848 Node prev = get();
849 Node next = prev.get();
850
851 int e = 0;
852 for (;;) {
853 if (size > 1) { // never truncate the very last item just added
854 if (size > limit) {
855 e++;
856 size--;
857 prev = next;
858 next = next.get();
859 } else {
860 Timed<?> v = (Timed<?>)next.value;
861 if (v.time() <= timeLimit) {
862 e++;
863 size--;
864 prev = next;
865 next = next.get();
866 } else {
867 break;
868 }
869 }
870 } else {
871 break;
872 }
873 }
874 if (e != 0) {
875 setFirst(prev);
876 }
877 }
878
879 @Override
880 void truncateFinal() {
881 long timeLimit = scheduler.now(unit) - maxAge;
882
883 Node prev = get();
884 Node next = prev.get();
885
886 int e = 0;
887 for (;;) {
888 if (size > 1) {
889 Timed<?> v = (Timed<?>)next.value;
890 if (v.time() <= timeLimit) {
891 e++;
892 size--;
893 prev = next;
894 next = next.get();
895 } else {
896 break;
897 }
898 } else {
899 break;
900 }
901 }
902 if (e != 0) {
903 setFirst(prev);
904 }
905 }
906
907 @Override
908 Node getHead() {
909 long timeLimit = scheduler.now(unit) - maxAge;
910 Node prev = get();
911 Node next = prev.get();
912 for (;;) {
913 if (next == null) {
914 break;
915 }
916 Timed<?> v = (Timed<?>)next.value;
917 if (NotificationLite.isComplete(v.value()) || NotificationLite.isError(v.value())) {
918 break;
919 }
920 if (v.time() <= timeLimit) {
921 prev = next;
922 next = next.get();
923 } else {
924 break;
925 }
926 }
927 return prev;
928 }
929 }
930
931 static final class UnBoundedFactory implements BufferSupplier<Object> {
932 @Override
933 public ReplayBuffer<Object> call() {
934 return new UnboundedReplayBuffer<>(16);
935 }
936 }
937
938 static final class DisposeConsumer<R> implements Consumer<Disposable> {
939 private final ObserverResourceWrapper<R> srw;
940
941 DisposeConsumer(ObserverResourceWrapper<R> srw) {
942 this.srw = srw;
943 }
944
945 @Override
946 public void accept(Disposable r) {
947 srw.setResource(r);
948 }
949 }
950
951 static final class ReplayBufferSupplier<T> implements BufferSupplier<T> {
952
953 final int bufferSize;
954
955 final boolean eagerTruncate;
956
957 ReplayBufferSupplier(int bufferSize, boolean eagerTruncate) {
958 this.bufferSize = bufferSize;
959 this.eagerTruncate = eagerTruncate;
960 }
961
962 @Override
963 public ReplayBuffer<T> call() {
964 return new SizeBoundReplayBuffer<>(bufferSize, eagerTruncate);
965 }
966 }
967
968 static final class ScheduledReplaySupplier<T> implements BufferSupplier<T> {
969 private final int bufferSize;
970 private final long maxAge;
971 private final TimeUnit unit;
972 private final Scheduler scheduler;
973
974 final boolean eagerTruncate;
975
976 ScheduledReplaySupplier(int bufferSize, long maxAge, TimeUnit unit, Scheduler scheduler, boolean eagerTruncate) {
977 this.bufferSize = bufferSize;
978 this.maxAge = maxAge;
979 this.unit = unit;
980 this.scheduler = scheduler;
981 this.eagerTruncate = eagerTruncate;
982 }
983
984 @Override
985 public ReplayBuffer<T> call() {
986 return new SizeAndTimeBoundReplayBuffer<>(bufferSize, maxAge, unit, scheduler, eagerTruncate);
987 }
988 }
989
990 static final class ReplaySource<T> implements ObservableSource<T> {
991 private final AtomicReference<ReplayObserver<T>> curr;
992 private final BufferSupplier<T> bufferFactory;
993
994 ReplaySource(AtomicReference<ReplayObserver<T>> curr, BufferSupplier<T> bufferFactory) {
995 this.curr = curr;
996 this.bufferFactory = bufferFactory;
997 }
998
999 @Override
1000 public void subscribe(Observer<? super T> child) {
1001 // concurrent connection/disconnection may change the state,
1002 // we loop to be atomic while the child subscribes
1003 for (;;) {
1004 // get the current subscriber-to-source
1005 ReplayObserver<T> r = curr.get();
1006 // if there isn't one
1007 if (r == null) {
1008 // create a new subscriber to source
1009 ReplayBuffer<T> buf = bufferFactory.call();
1010
1011 ReplayObserver<T> u = new ReplayObserver<>(buf, curr);
1012 // let's try setting it as the current subscriber-to-source
1013 if (!curr.compareAndSet(null, u)) {
1014 // didn't work, maybe someone else did it or the current subscriber
1015 // to source has just finished
1016 continue;
1017 }
1018 // we won, let's use it going onwards
1019 r = u;
1020 }
1021
1022 // create the backpressure-managing producer for this child
1023 InnerDisposable<T> inner = new InnerDisposable<>(r, child);
1024 // the producer has been registered with the current subscriber-to-source so
1025 // at least it will receive the next terminal event
1026 // setting the producer will trigger the first request to be considered by
1027 // the subscriber-to-source.
1028 child.onSubscribe(inner);
1029 // we try to add it to the array of observers
1030 // if it fails, no worries because we will still have its buffer
1031 // so it is going to replay it for us
1032 r.add(inner);
1033
1034 if (inner.isDisposed()) {
1035 r.remove(inner);
1036 return;
1037 }
1038
1039 // replay the contents of the buffer
1040 r.buffer.replay(inner);
1041
1042 break; // NOPMD
1043 }
1044 }
1045 }
1046
1047 static final class MulticastReplay<R, U> extends Observable<R> {
1048 private final Supplier<? extends ConnectableObservable<U>> connectableFactory;
1049 private final Function<? super Observable<U>, ? extends ObservableSource<R>> selector;
1050
1051 MulticastReplay(Supplier<? extends ConnectableObservable<U>> connectableFactory, Function<? super Observable<U>, ? extends ObservableSource<R>> selector) {
1052 this.connectableFactory = connectableFactory;
1053 this.selector = selector;
1054 }
1055
1056 @Override
1057 protected void subscribeActual(Observer<? super R> child) {
1058 ConnectableObservable<U> co;
1059 ObservableSource<R> observable;
1060 try {
1061 co = Objects.requireNonNull(connectableFactory.get(), "The connectableFactory returned a null ConnectableObservable");
1062 observable = Objects.requireNonNull(selector.apply(co), "The selector returned a null ObservableSource");
1063 } catch (Throwable e) {
1064 Exceptions.throwIfFatal(e);
1065 EmptyDisposable.error(e, child);
1066 return;
1067 }
1068
1069 final ObserverResourceWrapper<R> srw = new ObserverResourceWrapper<>(child);
1070
1071 observable.subscribe(srw);
1072
1073 co.connect(new DisposeConsumer<>(srw));
1074 }
1075 }
1076 }