Skip to content

Instantly share code, notes, and snippets.

@AAverin
Created June 13, 2016 13:47
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 AAverin/671877ccd8e6b6e1e588c7b398fd25a0 to your computer and use it in GitHub Desktop.
Save AAverin/671877ccd8e6b6e1e588c7b398fd25a0 to your computer and use it in GitHub Desktop.
A simple consistency manager implementation on Kotlin.
interface ConsistencyManagerContract {
fun notifyUpdateModel(model: Any)
fun notifyUpdateClass(kclass: KClass<*>)
fun subscribe(modelClass: KClass<*>, callback: WeakReference<(Any?) -> Unit>)
}
class ConsistencyManager : ConsistencyManagerContract {
private val subscriptionsMap: MutableMap<KClass<*>, MutableList<WeakReference<(Any?) -> Unit>>> = mutableMapOf()
override fun notifyUpdateModel(model: Any) {
val kotlinClass = model.javaClass.kotlin
subscriptionsMap[kotlinClass]?.forEach {
it.get()?.invoke(model)
}
}
override fun notifyUpdateClass(kclass: KClass<*>) {
subscriptionsMap[kclass]?.forEach {
it.get()?.invoke(null)
}
}
override fun subscribe(modelClass: KClass<*>, callback: WeakReference<(Any?) -> Unit>) {
var subscriptionsForModel = subscriptionsMap[modelClass]
if (subscriptionsForModel == null) {
subscriptionsForModel = mutableListOf(callback)
subscriptionsMap.put(modelClass, subscriptionsForModel)
} else {
if (subscriptionsForModel.firstOrNull() { it.get() == callback.get() } == null) {
subscriptionsForModel.add(callback)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment