com.nytimes.android.external.cache3.CacheLoader Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of cache3 Show documentation
Show all versions of cache3 Show documentation
Store3 is built with RxJava2
package com.nytimes.android.external.cache3;
import java.io.Serializable;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public abstract class CacheLoader {
/**
* Constructor for use by subclasses.
*/
protected CacheLoader() {}
/**
* Computes or retrieves the value corresponding to {@code key}.
*
* @param key the non-null key whose value should be loaded
* @return the value associated with {@code key}; must not be null
* @throws Exception if unable to load the result
* @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
* treated like any other {@code Exception} in all respects except that, when it is caught,
* the thread's interrupt status is set
*/
@Nullable
public abstract V load(K key) throws Exception;
@Nullable
public ListenableFuture reload(@Nonnull K key, @Nonnull V oldValue) throws Exception {
Preconditions.checkNotNull(key);
Preconditions.checkNotNull(oldValue);
return Futures.immediateFuture(load(key));
}
@Nonnull
public Map loadAll(Iterable extends K> keys) throws Exception {
// This will be caught by getAll(), causing it to fall back to multiple calls to
// LoadingCache.get
throw new UnsupportedLoadingOperationException();
}
/**
* Returns a cache loader based on an existing function instance. Note that there's no need
* to create a new function just to pass it in here; just subclass {@code CacheLoader} and
* implement {@link #load load} instead.
*
* @param function the function to be used for loading values; must never return {@code null}
* @return a cache loader that loads values by passing each key to {@code function}
*/
@Nonnull
public static CacheLoader from(@Nonnull Function function) {
return new FunctionToCacheLoader<>(function);
}
private static final class FunctionToCacheLoader
extends CacheLoader implements Serializable {
private final Function computingFunction;
public FunctionToCacheLoader(@Nonnull Function computingFunction) {
this.computingFunction = Preconditions.checkNotNull(computingFunction);
}
@Nullable
@Override
public V load(@Nonnull K key) {
return computingFunction.apply(Preconditions.checkNotNull(key));
}
private static final long serialVersionUID = 0;
}
/**
* Returns a cache loader based on an existing supplier instance. Note that there's no need
* to create a new supplier just to pass it in here; just subclass {@code CacheLoader} and
* implement {@link #load load} instead.
*
* @param supplier the supplier to be used for loading values; must never return {@code null}
* @return a cache loader that loads values by calling {@link Supplier#get}, irrespective of the
* key
*/
@Nonnull
public static CacheLoader