Search in sources :

Example 1 with TaskCompletionSource

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));
    }
}
Also used : RxWebSocketCallback(chat.rocket.android_ddp.rx.RxWebSocketCallback) TimeoutException(java.util.concurrent.TimeoutException) TextUtils(android.text.TextUtils) NonNull(android.support.annotation.NonNull) RCLog(chat.rocket.android.log.RCLog) TaskCompletionSource(bolts.TaskCompletionSource) TimeUnit(java.util.concurrent.TimeUnit) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) JSONException(org.json.JSONException) RxWebSocket(chat.rocket.android_ddp.rx.RxWebSocket) JSONObject(org.json.JSONObject) OkHttpClient(okhttp3.OkHttpClient) Flowable(io.reactivex.Flowable) Nullable(android.support.annotation.Nullable) Task(bolts.Task) JSONArray(org.json.JSONArray) JSONArray(org.json.JSONArray) RxWebSocketCallback(chat.rocket.android_ddp.rx.RxWebSocketCallback) CompositeDisposable(io.reactivex.disposables.CompositeDisposable)

Example 2 with TaskCompletionSource

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();
}
Also used : RealmObject(io.realm.RealmObject) TextUtils(android.text.TextUtils) HashMap(java.util.HashMap) UUID(java.util.UUID) RCLog(chat.rocket.android.log.RCLog) RealmObjectObserver(chat.rocket.persistence.realm.RealmObjectObserver) TaskCompletionSource(bolts.TaskCompletionSource) PrimaryKey(io.realm.annotations.PrimaryKey) JSONObject(org.json.JSONObject) RealmHelper(chat.rocket.persistence.realm.RealmHelper) SyncState(chat.rocket.core.SyncState) LogcatIfError(chat.rocket.persistence.realm.helpers.LogcatIfError) Task(bolts.Task) TaskCompletionSource(bolts.TaskCompletionSource) JSONObject(org.json.JSONObject) LogcatIfError(chat.rocket.persistence.realm.helpers.LogcatIfError) LogcatIfError(chat.rocket.persistence.realm.helpers.LogcatIfError)

Example 3 with TaskCompletionSource

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();
}
Also used : TaskCompletionSource(bolts.TaskCompletionSource) JSONException(org.json.JSONException) Realm(io.realm.Realm) JSONException(org.json.JSONException)

Example 4 with TaskCompletionSource

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;
        }
    });
}
Also used : Continuation(bolts.Continuation) Task(bolts.Task) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) JSONException(org.json.JSONException) FileInputStream(java.io.FileInputStream) TaskCompletionSource(bolts.TaskCompletionSource) File(java.io.File)

Example 5 with TaskCompletionSource

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();
}
Also used : TaskCompletionSource(bolts.TaskCompletionSource) AggregateException(bolts.AggregateException) CancellationException(java.util.concurrent.CancellationException)

Aggregations

TaskCompletionSource (bolts.TaskCompletionSource)11 JSONException (org.json.JSONException)9 Task (bolts.Task)7 TextUtils (android.text.TextUtils)6 RCLog (chat.rocket.android.log.RCLog)6 RxWebSocketCallback (chat.rocket.android_ddp.rx.RxWebSocketCallback)6 TimeoutException (java.util.concurrent.TimeoutException)6 JSONObject (org.json.JSONObject)6 NonNull (android.support.annotation.NonNull)5 Nullable (android.support.annotation.Nullable)5 RxWebSocket (chat.rocket.android_ddp.rx.RxWebSocket)5 Flowable (io.reactivex.Flowable)5 CompositeDisposable (io.reactivex.disposables.CompositeDisposable)5 TimeUnit (java.util.concurrent.TimeUnit)5 OkHttpClient (okhttp3.OkHttpClient)5 JSONArray (org.json.JSONArray)5 Realm (io.realm.Realm)2 AggregateException (bolts.AggregateException)1 Continuation (bolts.Continuation)1 SyncState (chat.rocket.core.SyncState)1