我正在寻找与xamarin
realm
中添加和读取数据相关的回调。
在这里,我正在从服务器获取数据并添加到 realm 中,但我想要一个事件,我可以在其中通知 UI company
数据已成功添加到 realm,如果出现任何错误,我也可以显示出来。
var content = await response.Content.ReadAsStringAsync();
Company company = JsonConvert.DeserializeObject<Company>(content);
Realm realm = Realm.GetInstance();
await realm.WriteAsync(tempRealm => {
tempRealm.Add(company);
});
在Android原生中,我们有以下功能在后台执行任何交易,并可以通知成功和失败。
final Realm realm = Realm.getInstance(App.getRealmConfig());
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(userResponseInfo.getCallInfoList());
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
}
}, new Realm.Transaction.OnError() {
@Override
public void onError(Throwable error) {
}
});
Realm Xamarin 使用从任务传播错误的标准 .NET 机制,这就是为什么您不需要成功和错误回调的原因。如果发生错误,将引发异常,可以在常规 try-catch 块中处理:
try
{
var realm = Realm.GetInstance();
await realm.WriteAsync(temp => temp.Add(company));
// if control reaches this line the transaction executed successfully.
notifier.NotifySuccess();
}
catch (Exception ex)
{
// The transaction failed - handle the exception
notifier.NotifyError(ex.Message);
}