Skip to content

Instantly share code, notes, and snippets.

@jorgevila
Created June 13, 2017 14:49
Show Gist options
  • Save jorgevila/5a169bedd48a3ffa30b1929c9238ec0b to your computer and use it in GitHub Desktop.
Save jorgevila/5a169bedd48a3ffa30b1929c9238ec0b to your computer and use it in GitHub Desktop.
Memoization single transformer
class MemoizationSingleTransformer<T : Expirable>(val expiration: Long) : SingleTransformer<T,
T> {
private val TAG: String? = MemoizationSingleTransformer::class.simpleName;
var value: T? = null
override fun apply(upstream: Single<T>): SingleSource<T>? {
val memory = Single.fromCallable {
value ?: Expirable().expire()
}.map {
Log.d(TAG, "[memory] " + it?.isExpired)
it
}
return Single.concat(memory, upstream.map {
Log.d(TAG, "[upstream] " + it.isExpired)
it
})
.filter { it?.isExpired != true }
.firstElement().toSingle().map {
value = it as T
value?.setExpiration(expiration)
it as T
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment