Created
June 13, 2016 13:47
-
-
Save AAverin/671877ccd8e6b6e1e588c7b398fd25a0 to your computer and use it in GitHub Desktop.
A simple consistency manager implementation on Kotlin.
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
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