可在地图上观察以检测何时添加、更新或删除条目

Gab*_*lle 2 delegates dictionary concurrenthashmap observable kotlin

我有一张地图,在我的例子中,ConcurrentHashMap<String, Device>它在接收到 websocket 上的一些事件时正在更新。我想在此地图上实现一个可观察的对象,以了解何时添加、更新或删除条目。我尝试使用ObservableProperty但当地图更改时没有调用任何方法。

var deviceCache : ConcurrentHashMap<String, Device> by MyObservable(ConcurrentHashMap())

 class MyObservable<T, V>(initialValue: ConcurrentHashMap<T, V>) : ObservableProperty<ConcurrentHashMap<T, V>>(initialValue) {
override fun afterChange(property: KProperty<*>, oldValue: ConcurrentHashMap<T, V>, newValue: ConcurrentHashMap<T, V>) {
  super.afterChange(property, oldValue, newValue)
  log.e("new value is $newValue")
}

override fun beforeChange(property: KProperty<*>, oldValue: ConcurrentHashMap<T, V>, newValue: ConcurrentHashMap<T, V>): Boolean {
  log.e("beforeChange called")
  return super.beforeChange(property, oldValue, newValue)
}
Run Code Online (Sandbox Code Playgroud)

}

谁能帮助我如何解决这个问题?

Ada*_*old 6

问题是这Map不是属性,您不能以这种方式使用属性委托。你所要做的就是编写一个装饰器,Map如下所示:

class ObservableMap<K, V>(private val map: MutableMap<K, V>) : MutableMap<K, V> by map {

    override fun put(key: K, value: V): V? {
        TODO("not implemented")
    }

    override fun putAll(from: Map<out K, V>) {
        TODO("not implemented")
    }

    override fun remove(key: K): V? {
        TODO("not implemented")
    }

}
Run Code Online (Sandbox Code Playgroud)

在这里,我们将所有操作委托给后台map,您只需在上述方法中添加/删除时实现您的逻辑即可。

我不确定你的意思update,但如果你的意思是“地图中的值被覆盖”,那么你可以在put.

你可以ObservableMap这样使用它:

val map = ObservableMap(ConcurrentHashMap<String, String>())
Run Code Online (Sandbox Code Playgroud)

请注意,如果您想支持 的操作,ConcurrentHashMap您还需要包含overridesforAbstractMap<K,V>ConcurrentMap<K,V>因为它们添加了您可能想要跟踪的一些新操作。上面的代码只是一个例子。