【问题标题】:Observable on map to detect when is added, updated of deleted an entry可在地图上观察以检测何时添加、更新或删除条目
【发布时间】:2019-06-04 09:00:58
【问题描述】:

我有一张地图,在我的例子中是ConcurrentHashMap<String, Device>,当在 websocket 上接收到一些事件时它正在更新。我想在这个地图上实现一个 observable,以了解何时添加、更新或删除条目。我尝试使用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)
}

}

谁能帮我解决这个问题?

【问题讨论】:

  • MyObservable 长什么样子?
  • @AdamArold 这是我的问题。
  • 哦,抱歉我看到了

标签: dictionary kotlin delegates observable concurrenthashmap


【解决方案1】:

问题是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")
    }

}

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

我不确定您所说的 update 是什么意思,但如果您的意思是“地图中的某个值被覆盖”,那么您可以在 put 中处理它。

你可以像这样使用ObservableMap

val map = ObservableMap(ConcurrentHashMap<String, String>())

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

【讨论】:

  • 谢谢,效果很好。还有一个问题:我在服务层上有这个缓存(它是一个 java 库模块)。我需要在 viewModel 中将这些通知(何时添加、更新或删除)发送到表示层(android 层)。我看到的唯一解决方案是使用侦听器。是否可以使用这个装饰器来通知 UI 这些变化?服务层不知道表现层,只有表现层知道服务层。
  • 我可能会使用事件总线。你试过this one吗?
  • 不,我必须在没有库的情况下实现。
  • 你可以轻松写一篇。 Here 就是一个例子。
猜你喜欢
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-21
  • 2020-02-06
  • 2011-11-16
  • 1970-01-01
相关资源
最近更新 更多