Observable Models
FlowContentObserver
可用于监听Model
的数据变化。它是ContentObserver
类的一个包装以添加对Uri事件的监听。你可以创建一个观察者observer然后向里面添加一些OnModelStateChangeListener
以响应model的数据变化事件。
NOTE:需要Android API16+
如何使用
创建一个FlowContentObserver
:
FlowContentObserver observer = new FlowContentObserver();
// registers for callbacks from the specified table
observer.registerForContentChanges(context, TestNotifiableModel.class);
// call this to release itself from content changes
observer.unregisterForContentChanges(context);
创建Table类:
@Table(database = SomeDatabase.class)
public class TestNotifiableModel extends BaseModel {
@PrimaryKey
String name;
}
创建一个回调:
FlowContentObserver.OnModelStateChangeListener modelChangeListener = new FlowContentObserver.OnModelStateChangeListener() {
@Override
public void onModelStateChanged(Class<? extends Model> table, Action action, SQLCondition[] primaryKeyValues) {
}
};
将回调添加到观察者里:
observer.addModelChangeListener(modelChangeListener);
TestNotifiableModel testModel = new TestNotifiableModel();
testModel.setName("myName");
// will notify our observer automatically, no configuration needed!
testModel.insert();
testModel.update();
testModel.save();
testModel.delete();
// when done with listener
observer.removeModelChangeListener(modelChangeListener);
打包事务通知
通过beginTransaction()...endTransactionAndNotify()
方法,我们能将所有包含其中的通知事件打包在最后统一发送:
flowContentObserver.beginTransaction();
someModel.save();
// More modifications on a table for what the Flow Content Observer is registered.
// collects all unique URI and calls onChange here
flowContentObserver.endTransactionAndNotify();