use of chat.rocket.persistence.realm.RealmObjectObserver in project Rocket.Chat.Android by RocketChat.
the class MethodCall method execute.
/**
* insert a new record to request a method call.
*/
public static Task<String> execute(RealmHelper realmHelper, String name, String paramsJson, long timeout) {
final String newId = UUID.randomUUID().toString();
TaskCompletionSource<String> task = new TaskCompletionSource<>();
realmHelper.executeTransaction(realm -> {
MethodCall call = realm.createObjectFromJson(MethodCall.class, new JSONObject().put(ID, newId).put(SYNC_STATE, SyncState.NOT_SYNCED).put(TIMEOUT, timeout).put(NAME, name));
call.setParamsJson(paramsJson);
return null;
}).continueWith(_task -> {
if (_task.isFaulted()) {
task.setError(_task.getError());
} else {
final RealmObjectObserver<MethodCall> observer = realmHelper.createObjectObserver(realm -> realm.where(MethodCall.class).equalTo(ID, newId));
observer.setOnUpdateListener(methodCall -> {
if (methodCall == null) {
observer.unsub();
REF_MAP.remove(newId);
return;
}
int syncState = methodCall.getSyncState();
RCLog.d("MethodCall[%s] syncstate=%d", methodCall.getMethodCallId(), syncState);
if (syncState == SyncState.SYNCED) {
String resultJson = methodCall.getResultJson();
if (TextUtils.isEmpty(resultJson)) {
task.setResult(null);
} else {
task.setResult(resultJson);
}
observer.unsub();
REF_MAP.remove(methodCall.getMethodCallId());
remove(realmHelper, methodCall.getMethodCallId()).continueWith(new LogcatIfError());
} else if (syncState == SyncState.FAILED) {
task.setError(new Error(methodCall.getResultJson()));
observer.unsub();
REF_MAP.remove(methodCall.getMethodCallId());
remove(realmHelper, methodCall.getMethodCallId()).continueWith(new LogcatIfError());
}
});
observer.sub();
REF_MAP.put(newId, observer);
}
return null;
});
return task.getTask();
}
Aggregations