use of bolts.TaskCompletionSource in project Rocket.Chat.Android by RocketChat.
the class DDPClientImpl method sub.
public void sub(final TaskCompletionSource<DDPSubscription.Ready> task, String name, JSONArray params, String id) {
final boolean requested = sendMessage("sub", json -> json.put("id", id).put("name", name).put("params", params));
if (requested) {
CompositeDisposable subscriptions = new CompositeDisposable();
subscriptions.add(flowable.filter(callback -> callback instanceof RxWebSocketCallback.Message).map(callback -> ((RxWebSocketCallback.Message) callback).responseBodyString).map(DDPClientImpl::toJson).subscribe(response -> {
String msg = extractMsg(response);
if ("ready".equals(msg) && !response.isNull("subs")) {
JSONArray ids = response.optJSONArray("subs");
for (int i = 0; i < ids.length(); i++) {
String _id = ids.optString(i);
if (id.equals(_id)) {
task.setResult(new DDPSubscription.Ready(client, id));
subscriptions.dispose();
break;
}
}
} else if ("nosub".equals(msg) && !response.isNull("id") && !response.isNull("error")) {
String _id = response.optString("id");
if (id.equals(_id)) {
task.setError(new DDPSubscription.NoSub.Error(client, id, response.optJSONObject("error")));
subscriptions.dispose();
}
}
}, err -> {
}));
addErrorCallback(subscriptions, task);
} else {
task.trySetError(new DDPClientCallback.Closed(client));
}
}
use of bolts.TaskCompletionSource 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();
}
use of bolts.TaskCompletionSource in project Rocket.Chat.Android by RocketChat.
the class RealmHelper method executeTransactionAsync.
private Task<Void> executeTransactionAsync(final RealmHelper.Transaction transaction) {
final TaskCompletionSource<Void> task = new TaskCompletionSource<>();
final Realm realm = instance();
realm.executeTransactionAsync(_realm -> {
try {
transaction.execute(_realm);
} catch (JSONException exception) {
throw new RuntimeException(exception);
}
}, () -> {
realm.close();
task.setResult(null);
}, error -> {
realm.close();
if (error instanceof Exception) {
task.setError((Exception) error);
} else {
task.setError(new Exception(error));
}
});
return task.getTask();
}
use of bolts.TaskCompletionSource in project Parse-SDK-Android by ParsePlatform.
the class ParseFile method getDataStreamInBackground.
/**
* Asynchronously gets the data stream from cached file if available or fetches its content from
* the network, saves the content as cached file and returns the data stream of the cached file.
* The {@code ProgressCallback} will be called periodically with progress updates.
*
* @param progressCallback
* A {@code ProgressCallback} that is called periodically with progress updates.
* @return A Task that is resolved when the data stream of this object has been fetched.
*/
public Task<InputStream> getDataStreamInBackground(final ProgressCallback progressCallback) {
final TaskCompletionSource<Void> cts = new TaskCompletionSource<>();
currentTasks.add(cts);
return taskQueue.enqueue(new Continuation<Void, Task<InputStream>>() {
@Override
public Task<InputStream> then(Task<Void> toAwait) throws Exception {
return fetchInBackground(progressCallback, toAwait, cts.getTask()).onSuccess(new Continuation<File, InputStream>() {
@Override
public InputStream then(Task<File> task) throws Exception {
return new FileInputStream(task.getResult());
}
});
}
}).continueWithTask(new Continuation<InputStream, Task<InputStream>>() {
@Override
public Task<InputStream> then(Task<InputStream> task) throws Exception {
// release
cts.trySetResult(null);
currentTasks.remove(cts);
return task;
}
});
}
use of bolts.TaskCompletionSource in project Parse-SDK-Android by ParsePlatform.
the class ParseTaskUtils method callbackOnMainThreadAsync.
/**
* Calls the callback after a task completes on the main thread, returning a Task that completes
* with the same result as the input task after the callback has been run. If reportCancellation
* is false, the callback will not be called if the task was cancelled.
*/
/* package */
static <T> Task<T> callbackOnMainThreadAsync(Task<T> task, final ParseCallback2<T, ParseException> callback, final boolean reportCancellation) {
if (callback == null) {
return task;
}
final TaskCompletionSource<T> tcs = new TaskCompletionSource();
task.continueWith(new Continuation<T, Void>() {
@Override
public Void then(final Task<T> task) throws Exception {
if (task.isCancelled() && !reportCancellation) {
tcs.setCancelled();
return null;
}
ParseExecutors.main().execute(new Runnable() {
@Override
public void run() {
try {
Exception error = task.getError();
if (error != null && !(error instanceof ParseException)) {
error = new ParseException(error);
}
callback.done(task.getResult(), (ParseException) error);
} finally {
if (task.isCancelled()) {
tcs.setCancelled();
} else if (task.isFaulted()) {
tcs.setError(task.getError());
} else {
tcs.setResult(task.getResult());
}
}
}
});
return null;
}
});
return tcs.getTask();
}
Aggregations