Skip to content

Instantly share code, notes, and snippets.

@sergiandreplace
Created August 19, 2016 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergiandreplace/e10e29c6cb3d47a4bb758e647fb01bdf to your computer and use it in GitHub Desktop.
Save sergiandreplace/e10e29c6cb3d47a4bb758e647fb01bdf to your computer and use it in GitHub Desktop.
Attempt to create a caching system that can be integrated into rx
package com.scmspain.bluejobs.candidateagent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import rx.Observable;
public abstract class Cache<I, T> {
private Map<I, CachedObject<T>> cachedItems = new HashMap<>();
private long expirationTime = 5 * 60 * 1000; // 5 minutes
public Cache(long expirationTime) {
this.expirationTime = expirationTime;
}
public Observable<T> retrieve(I index) {
return Observable.from(cachedItems.values())
.filter(cachedItem -> cachedItem.getIndex() == index)
.filter(cachedItem -> cachedItem.getTimestamp() < System.currentTimeMillis() - expirationTime)
.map(CachedObject::getItem);
}
public Observable.Transformer<T, T> save(I index, T item) {
return input -> input.doOnNext(t -> cachedItems.put(index, new CachedObject<>(index, item, System.currentTimeMillis())));
}
private class CachedObject<T> {
private final T item;
private final I index;
private final Long timestamp;
public CachedObject(I index, T item, Long timestamp) {
this.item = item;
this.index = index;
this.timestamp = timestamp;
}
public T getItem() {
return item;
}
public I getIndex() {
return index;
}
public Long getTimestamp() {
return timestamp;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment