是否有一种简洁的方法来仅获取child added
或任何事件?现在,我必须执行以下操作,看起来很愚蠢
ref.addChildEventListener(object : ChildEventListener {
override fun onCancelled(p0: DatabaseError) {}
override fun onChildChanged(p0: DataSnapshot, p1: String?) {}
override fun onChildMoved(p0: DataSnapshot, p1: String?) {}
override fun onChildRemoved(p0: DataSnapshot) {}
override fun onChildAdded(p0: DataSnapshot, p1: String?) {
subscriber.onNext(Value.parse(unitName, varName, p0))
}
})
答案 0 :(得分:1)
您可以创建自己的抽象类,该抽象类实现ChildEventListener,但不提供onChildAdded的实现:
abstract class ChildAddedEventListener : ChildEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onChildMoved(p0: DataSnapshot, p1: String?) {
}
override fun onChildChanged(p0: DataSnapshot, p1: String?) {
}
override fun onChildRemoved(p0: DataSnapshot) {
}
}
然后,您将ChildAddedEventListener子类化,并仅提供所需的实现:
class MyChildAddedEventListener: ChildAddedEventListener {
override fun onChildAdded(p0: DataSnapshot, p1: String?) {
// your code here
}
}
有了它,您可以在将其添加到查询中时将其用作内联对象表达式:
query.addChildEventListener(object : ChildAddedEventListener() {
override fun onChildAdded(p0: DataSnapshot, p1: String?) {
subscriber.onNext(Value.parse(unitName, varName, p0))
}
})
答案 1 :(得分:0)
在您的情况下,通常省略所有方法的模式的名称称为Adapter:
$recruits
(接口)适配器类是使用空方法实现接口的类,因此您可以选择要覆盖的那个
答案 2 :(得分:0)
您可以
object EmptyChildEventListener : ChildEventListener {
override fun onCancelled(p0: DatabaseError) {}
override fun onChildChanged(p0: DataSnapshot, p1: String?) {}
override fun onChildMoved(p0: DataSnapshot, p1: String?) {}
override fun onChildRemoved(p0: DataSnapshot) {}
override fun onChildAdded(p0: DataSnapshot, p1: String?) { }
}
ref.addChildEventListener(object : ChildEventListener by EmptyChildEventListener {
override fun onChildAdded(p0: DataSnapshot, p1: String?) {
subscriber.onNext(Value.parse(unitName, varName, p0))
}
})
编辑:,但是您可以像这样改善它
inline fun DatabaseReference.onChildAdded(crossinline added: (DataSnapshot, String?) -> Unit) {
this.addChildEventListener(object : ChildEventListener by EmptyChildEventListener {
override fun onChildAdded(p0: DataSnapshot, p1: String?) = added(p0, p1)
})
})
现在您可以做
ref.onChildAdded { p0, p1 ->
subscriber.onNext(Value.parse(unitName, varName, p0))
}