Interface Promise<T>

  • Type Parameters:
    T - the type of values instances of this class resolve to in case they complete normally.

    public interface Promise<T>
    Implementation of the promise pattern, used for composing async program flows. All asynchronous operations within the Tapkey Mobile SDK will return instances of this class.

    Promises allow waiting for the outcome of an operation in an async manner. Instead of waiting synchronously, callbacks, so called continuations, can be registered that are invoked on completion.

    Async functions returning promises can be composed to build async flows.

    Continuations are run on the AsyncScheduler a promise was created with. Methods of this class that return a Promise, like continueOnUi(Func1), catchOnUi(Func1), etc., capture the AsyncScheduler as returned by AsyncSchedulers.current() at the time the method is called and associate it with the returned Promise.

    Most often promises are produced and continuations registered on the UI thread, which implies, that continuations will also run on the UI thread and subsequent Promises are also associated with the UI thread. This is why functions for registering continuations contain the term 'Ui'. Running all functionality on the UI thread makes synchronization between async functions very easy, because there is no multi-threading involved. This implies, however, that these functions may only run for a very short period of time in order not to compromise the user experience. Long running operations should be run on a separate worker thread by switching to an according AsyncScheduler or by using Async.executeAsync(Func).

    The following exemplary code demonstrates an asynchronous method that returns a Promise.

     public Promise<String> getStringAsync() {
         PromiseSource<String> promiseSource = new PromiseSource<>();
    
         // Trigger a long-running operation
         getStringFromServer((text, ex) -> {
             if (ex) {
                 promiseSource.setException(ex);
                 return;
             }
             promiseSource.setResult(text);
         });
         return promiseSource.getPromise();
     }
     

    The example code below illustrates how to chain promises:

     getTextFromServer()
         .continueAsyncOnUi(text -> uploadTextToAnotherServer(text))
         .continueOnUi(result -> {
             Log.d(TAG, "Upload completed: " + result);
             return null;
         })
         .catchOnUi(e -> {
             Log.e(TAG, "Something went wrong.", e);
             return null;
         })
         .conclude();
     

    See Also:
    https://en.wikipedia.org/wiki/Futures_and_promises, Async
    • Method Detail

      • getResult

        AsyncResult<? extends T> getResult()
        Returns the promised async result if this promise is completed. Returns null if the promise is not yet completed.
        Returns:
        the promised AsyncResult if this Promise is completed or null, if not.
      • register

        void register​(AsyncCallback<? super T> continuation)
        Registers a callback which will be invoked on this instance's scheduler with an AsyncResult, as soon as the underlying task is completed. The passed on async result's AsyncResult.get() will raise an AsyncException if the underlying task failed.
        Parameters:
        continuation - the callback that will be invoked on this instance's scheduler as soon as the underlying task is completed.
      • continueOnUi

        <TNext> Promise<TNext> continueOnUi​(Func1<? super T,​TNext,​? extends Exception> continuation)
        Registers a function which will be invoked on this instance's scheduler as soon as the underlying task has completed successfully. If either the underlying task or the continuation fails, the exception will be reflected by the promise returned by this method. This way calls can be chained and only the last promise in the chain needs to be inspected for exceptional completion. The returned Promise will be associated with the scheduler current at the time this method is invoked.
        Parameters:
        continuation - the callback that will be invoked on this instance's scheduler as soon as the underlying task is completed successfully.
        Returns:
        a Promise reflecting the outcome of this instance if exceptional, or the outcome of the continuation otherwise.
      • continueOnUiWithAsyncResult

        <TNext> Promise<TNext> continueOnUiWithAsyncResult​(Func1<AsyncResult<? extends T>,​TNext,​? extends Exception> continuation)
        Registers a function which will be invoked on this instance's scheduler as soon as the underlying task is completed successfully. The promise returned by this method will provide the continuation's result on the current scheduler. If either the underlying task or the continuation fails, the exception will be reflected by the Promise returned by this method. This way calls can be chained and only the last promise in the chain needs to be inspected for exceptional completion. The returned Promise will be associated with the scheduler current at the time this method is invoked.
        Parameters:
        continuation - the callback that will be invoked on this instance's scheduler as soon as the underlying task is completed.
        Returns:
        a Promise reflecting the outcome of this instance if exceptional, or the outcome of the continuation otherwise.
      • continueAsyncOnUi

        <TNext> Promise<TNext> continueAsyncOnUi​(Func1<? super T,​Promise<TNext>,​? extends Exception> continuation)
        Registers an async function which will be invoked on this instance's scheduler as soon as the underlying task completed successfully. The promise returned by this method will provide the continuation's result on the current scheduler as soon as the continuation is completed. If either the underlying task or the continuation fails, the exception will be reflected by the Promise returned by this method. This way calls can be chained and only the last promise in the chain needs to be inspected for exceptional completion. The returned Promise will be associated with the scheduler current at the time this method is invoked.
        Parameters:
        continuation - the callback that will be invoked on this instance's scheduler as soon as the underlying task is completed.
        Returns:
        a Promise reflecting the outcome of this instance if exceptional, or the outcome of the continuation otherwise.
      • continueAsyncOnUiWithAsyncResult

        <TNext> Promise<TNext> continueAsyncOnUiWithAsyncResult​(Func1<AsyncResult<? extends T>,​Promise<TNext>,​? extends Exception> continuation)
        Registers an async function which will be invoked on this instance's scheduler as soon as the underlying task completed successfully. The promise returned by this method will provide the continuation's result on the current scheduler. If either the underlying task or the continuation fails, the exception will be reflected by the Promise returned by this method. This way calls can be chained and only the last promise in the chain needs to be inspected for exceptional completion. The returned Promise will be associated with the scheduler current at the time this method is invoked.
        Parameters:
        continuation - the callback that will be invoked on this instance's scheduler as soon as the underlying task is completed.
        Returns:
        a Promise reflecting the outcome of this instance if exceptional, or the outcome of the continuation otherwise.
      • finallyOnUi

        Promise<T> finallyOnUi​(Action<? extends Exception> finallyBlock)
        Registers an Action which is invoked on this instance's scheduler as soon as the underlying task is completed, regardless of whether it completes successfully or exceptionally. The returned Promise will be associated with the scheduler current at the time this method is invoked.
        Parameters:
        finallyBlock - the action that will be invoked on this instance's scheduler as soon as the underlying task is completed.
        Returns:
        a promise that completes with the same result as this promise after the given finallyBlock completed.
      • finallyAsyncOnUi

        Promise<T> finallyAsyncOnUi​(Func<Promise<Void>,​? extends Exception> finallyBlock)
        Registers an async function which will be invoked on this instance's scheduler as soon as the underlying task is completed, regardless of whether it completes successfully or exceptionally. The returned Promise will be associated with the scheduler current at the time this method is invoked.
        Parameters:
        finallyBlock - the async function that will be invoked on this instance's scheduler as soon as the underlying task is completed.
        Returns:
        a promise that completes with the same result as this promise after the given finallyBlock completed.
      • catchOnUi

        Promise<T> catchOnUi​(Func1<AsyncException,​T,​? extends Exception> exceptionHandler)
        Registers an Action which is invoked on this instance's scheduler if this task completes exceptionally. In this case the returned Promise will reflect the outcome of the registered exceptionHandler. Otherwise it will reflect the result of this instance. The returned Promise will be associated with the scheduler current at the time this method is invoked.
        Parameters:
        exceptionHandler - the function that will be invoked on this instance's scheduler if the underlying Promise completes exceptionally.
        Returns:
        a promise that completes either with the same result as this promise, if successful, or with the result of the given exceptionHandler, if this promise completes exceptionally.
      • catchAsyncOnUi

        Promise<T> catchAsyncOnUi​(Func1<AsyncException,​Promise<T>,​RuntimeException> exceptionHandler)
        Registers an async function which is invoked on this instance's scheduler if this task completes exceptionally. In this case the returned Promise will reflect the outcome of the registered async exceptionHandler. Otherwise it will reflect the result of this instance. The returned Promise will be associated with the scheduler current at the time this method is invoked.
        Parameters:
        exceptionHandler - the async function that will be invoked on this instance's scheduler if the underlying Promise completes exceptionally.
        Returns:
        a promise that completes either with the same result as this promise, if successful, or with the result of the given exceptionHandler, if this promise completes exceptionally.
      • asVoid

        Promise<Void> asVoid()
        Converts this Promise into one returning null of type Void. If this instance completes normally, the returned promise will complete with null, otherwise it will reflect the Exception this instance resolves to. The returned Promise will be associated with the scheduler current at the time this method is invoked.
        Returns:
        this instance converted to Void.
      • asConst

        <TConvert> Promise<TConvert> asConst​(TConvert value)
        Converts this Promise into one returning the specified value. If this instance completes normally, the returned promise will complete with the given value, otherwise it will reflect the Exception this instance resolves to. The returned Promise will be associated with the scheduler current at the time this method is invoked.
        Returns:
        this instance converted to the given value.
      • conclude

        void conclude()
        Concludes an async flow. This function should be called on Promises which aren't resolved otherwise. This is to make sure, the final outcome of an async flow isn't lost. This is especially useful if an async flow ends exceptionally. In this case, if the last promise returned by the chain of async calls isn't handled, the Exception it resolves to would get lost. A call to this function ensures, any exception that hasn't been handled is treated as unhandled exception.
      • cancelable

        Promise<T> cancelable​(CancellationToken cancellationToken,
                              boolean forceImmediately)
        Allows a promise chain being cancelled. Cancelling the token passed to this function doesn't actually cancel the operations represented by this Promise. Instead it prevents the following operations from running normally by setting the result of the returned Promise to a CancellationException. Note: If the operation represented by this Promise is to be interrupted, the CancellationToken must be passed to the corresponding function directly, which must handle cancellation. The returned Promise will be associated with the scheduler current at the time this method is invoked.
        Parameters:
        cancellationToken - the cancellation token.
        forceImmediately - when set to false, the current Promise will run to an end, before the returned Promise is completed. If set to true, the returned Promise is completed immediately if the cancellationToken requests cancellation.
        Returns:
        A promise that is set to a CancellationException if the passed CancellationToken is cancelled.