Created
June 13, 2017 14:49
-
-
Save jorgevila/5a169bedd48a3ffa30b1929c9238ec0b to your computer and use it in GitHub Desktop.
Memoization single transformer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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