Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions src/main/java/rx/Single.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import rx.functions.*;
import rx.internal.operators.*;
import rx.internal.util.*;
import rx.observables.ConnectableObservable;
import rx.observers.*;
import rx.plugins.RxJavaHooks;
import rx.schedulers.Schedulers;
Expand Down Expand Up @@ -1269,6 +1270,62 @@ public static <R> Single<R> zip(Iterable<? extends Single<?>> singles, FuncN<? e
return SingleOperatorZip.zip(iterableToArray, zipFunction);
}

/**
* Returns a Single that subscribes to this Single lazily, caches its success or error event
* and replays it to all the downstream subscribers.
* <p>
* <img width="640" height="410" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/cache.png" alt="">
* <p>
* This is useful when you want a Single to cache its response and you can't control the
* subscribe/unsubscribe behavior of all the {@link Subscriber}s.
* <p>
* The operator subscribes only when the first downstream subscriber subscribes and maintains
* a single subscription towards this Single. In contrast, the operator family of {@link Observable#replay()}
* that return a {@link ConnectableObservable} require an explicit call to {@link ConnectableObservable#connect()}.
* <p>
* <em>Note:</em> You sacrifice the ability to unsubscribe from the origin when you use the {@code cache}
* Observer so be careful not to use this Observer on Observables that emit an infinite or very large number
* of items that will use up memory.
* A possible workaround is to apply `takeUntil` with a predicate or
* another source before (and perhaps after) the application of cache().
* <pre><code>
* AtomicBoolean shouldStop = new AtomicBoolean();
*
* source.takeUntil(v -&gt; shouldStop.get())
* .cache()
* .takeUntil(v -&gt; shouldStop.get())
* .subscribe(...);
* </code></pre>
* Since the operator doesn't allow clearing the cached values either, the possible workaround is
* to forget all references to it via {@link Observable#onTerminateDetach()} applied along with the previous
* workaround:
* <pre><code>
* AtomicBoolean shouldStop = new AtomicBoolean();
*
* source.takeUntil(v -&gt; shouldStop.get())
* .onTerminateDetach()
* .cache()
* .takeUntil(v -&gt; shouldStop.get())
* .onTerminateDetach()
* .subscribe(...);
* </code></pre>
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator consumes this Single in an unbounded fashion but respects the backpressure
* of each downstream Subscriber individually.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code cache} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @return a Single that, when first subscribed to, caches its response for the
* benefit of subsequent subscribers
* @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a>
*/
@Experimental
public final Single<T> cache() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New operators need @Experimental annotation.

return toObservable().cacheWithInitialCapacity(1).toSingle();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose this is a start. Ideally we would have a dedicated operator implementation that was low-overhead since we know the only thing that needs cached is a single item or complete.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I figured I'd go for the low hanging fruit of just getting a working API out there rather than try and tackle some implementation of CachedSingle all at once.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought @JakeWharton wanted a native Single.cache and not this type of reuse.

}

/**
* Returns an Observable that emits the item emitted by the source Single, then the item emitted by the
* specified Single.
Expand Down
47 changes: 47 additions & 0 deletions src/test/java/rx/SingleTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,53 @@ public void testReturnUnsubscribedWhenHookThrowsError() {
assertTrue(subscription.isUnsubscribed());
}

@Test
public void testCache() throws InterruptedException {
final AtomicInteger counter = new AtomicInteger();
Single<String> s = Single.create(new OnSubscribe<String>() {

@Override
public void call(final SingleSubscriber<? super String> observer) {
new Thread(new Runnable() {

@Override
public void run() {
counter.incrementAndGet();
observer.onSuccess("one");
}
}).start();
}
}).cache();

// we then expect the following 2 subscriptions to get that same value
final CountDownLatch latch = new CountDownLatch(2);

// subscribe once
s.subscribe(new Action1<String>() {

@Override
public void call(String v) {
assertEquals("one", v);
latch.countDown();
}
});

// subscribe again
s.subscribe(new Action1<String>() {

@Override
public void call(String v) {
assertEquals("one", v);
latch.countDown();
}
});

if (!latch.await(1000, TimeUnit.MILLISECONDS)) {
fail("subscriptions did not receive values");
}
assertEquals(1, counter.get());
}

@Test
public void testCreateSuccess() {
TestSubscriber<String> ts = new TestSubscriber<String>();
Expand Down