我正在尝试代理Observables和LiveData的调用(类似于Mediator模式),但我找不到类型安全的解决方案。这就是问题所在:
class Proxy {
private val backupMap = HashMap<LiveData<Any>, Observer<Any>>()
fun <T> add(liveData : LiveData<T>, observer : Observer<T>) {
// !This is the issue LiveData<Any> is expected
backupMap.put(liveData, observer)
}
fun attach() {
backupMap.forEach { (key, value) ->
key.observeForever(value)
}
}
}
fun addSome() {
Proxy().apply {
add(MutableLiveData<String>(), Observer { })
}
}
我可以将backupMap.put
投放到backupMap.put(liveData as LiveData<Any>, observer as Observer<Any>)
,但这会导致Unchecked Cast
。
答案 0 :(得分:0)
我发现的解决方案是使用中间对象来保存类型安全绑定:
private val backupMap: MutableMap<LiveData<*>, Attacher<*>>
private class Attacher<A>(private val lifeData: LiveData<A>, private val observer : Observer<A>) {
fun attach() {
lifeData.observeForever(observer)
}
fun detach() {
lifeData.removeObserver(observer)
}
}