TKMPromise

public class TKMPromise<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 TKMAsyncScheduler a promise was created with. Methods of this class that return a TKMPromise<T>, like continueOnUi(continuation:), catchOnUi(errorHandler:), etc., capture the TKMAsyncScheduler as returned by TKMAsyncSchedulers.current() at the time the method is called and associate it with the returned TKMPromise<T>.

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 TKMPromise<T>s 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 TKMAsyncScheduler or by using TKMAsync.executeAsync(f:).

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

public func getStringAsync() -> TKPromise<String> {
    let promiseSource = TKMPromiseSource<String>()

    // Trigger a long-running operation
    getStringFromServer {(text: String?, optError: Error?) -> Void in
        if let error = optError {
            promiseSource.setError(error)
            return
        }
        promiseSource.setResult(text)
    }
    return promiseSource.promise
}

The example code below illustrates how to chain promises:

getTextFromServer()
    .continueAsyncOnUi { text in
        return uploadTextToAnotherServer(text)
    }
    .continueOnUi { result in
        TKMLog.d(TAG, "Upload completed: \(result)")
        return nil
    }
    .catchOnUi { e in
        TKMLog.e(TAG, "Something went wrong.", e)
        return nil
    }
    .conclude()

See also

TKMAsync
  • Returns the promised async result if this promise is completed. Returns null if the promise is not yet completed.

    Declaration

    Swift

    public var result: (() throws -> T?)? { get }
  • Registers a callback which will be invoked on this instance’s scheduler with an async result, as soon as the underlying task is completed. The passed on async result’s function will raise an TKMAsyncError if the underlying task failed.

    Declaration

    Swift

    public func register(_ continuation: @escaping ( @escaping () throws -> T? ) -> Void ) -> Void

    Parameters

    continuation

    the callback that will be invoked on this instance’s scheduler as soon as the underlying task is completed.

  • 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 error 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 TKMPromise<T> will be associated with the scheduler current at the time this method is invoked.

    Declaration

    Swift

    public func continueOnUi<TNext>(_ continuation: @escaping (T?) throws -> TNext?) -> TKMPromise<TNext>

    Parameters

    continuation

    the callback that will be invoked on this instance’s scheduler as soon as the underlying task is completed successfully.

    Return Value

    a TKMPromise<T> reflecting the outcome of this instance if exceptional, or the outcome of the continuation otherwise.

  • 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 error 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 TKMPromise<T> will be associated with the scheduler current at the time this method is invoked.

    Declaration

    Swift

    public func continueOnUiWithAsyncResult<TNext>(_ continuation: @escaping (() throws -> T?) throws -> TNext?) -> TKMPromise<TNext>

    Parameters

    continuation

    the callback that will be invoked on this instance’s scheduler as soon as the underlying task is completed.

    Return Value

    a TKMPromise<T> reflecting the outcome of this instance if exceptional, or the outcome of the continuation otherwise.

  • 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 error 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 TKMPromise<T> will be associated with the scheduler current at the time this method is invoked.

    Declaration

    Swift

    public func continueAsyncOnUi<TNext>(_ continuation: @escaping (T?) -> TKMPromise<TNext>) -> TKMPromise<TNext>

    Parameters

    continuation

    the callback that will be invoked on this instance’s scheduler as soon as the underlying task is completed.

    Return Value

    a TKMPromise<T> reflecting the outcome of this instance if exceptional, or the outcome of the continuation otherwise.

  • 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 error 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 TKMPromise<T> will be associated with the scheduler current at the time this method is invoked.

    Declaration

    Swift

    public func continueAsyncOnUiWithAsyncResult<TNext>(_ continuation: @escaping (() throws -> T?) -> TKMPromise<TNext>) -> TKMPromise<TNext>

    Return Value

    a TKMPromise<T> reflecting the outcome of this instance if exceptional, or the outcome of the continuation otherwise.

  • Registers an TKMAction 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 TKMPromise<T> will be associated with the scheduler current at the time this method is invoked.

    Declaration

    Swift

    public func finallyOnUi(_ finallyBlock: @escaping () throws -> Void) -> TKMPromise<T>

    Return Value

    a promise that completes with the same result as this promise after the given finallyBlock completed.

  • 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 TKMPromise<T> will be associated with the scheduler current at the time this method is invoked.

    Declaration

    Swift

    public func finallyAsyncOnUi(_ finallyBlock: @escaping () -> TKMPromise<Void> ) -> TKMPromise<T>

    Return Value

    a promise that completes with the same result as this promise after the given finallyBlock completed.

  • Registers an TKMAction which is invoked on this instance’s scheduler if this task completes exceptionally. In this case the returned TKMPromise<T> will reflect the outcome of the registered errorHandler. Otherwise it will reflect the result of this instance.

    The returned TKMPromise<T> will be associated with the scheduler current at the time this method is invoked.

    Declaration

    Swift

    public func catchOnUi(_ errorHandler: @escaping (TKMAsyncError) throws -> T?) -> TKMPromise<T>

    Return Value

    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.

  • Registers an async function which is invoked on this instance’s scheduler if this task completes exceptionally. In this case the returned TKMPromise<T> will reflect the outcome of the registered async errorHandler. Otherwise it will reflect the result of this instance.

    The returned TKMPromise<T> will be associated with the scheduler current at the time this method is invoked.

    Declaration

    Swift

    public func catchAsyncOnUi(_ errorHandler: @escaping (TKMAsyncError) -> TKMPromise<T> ) -> TKMPromise<T>

    Return Value

    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.

  • Converts this TKMPromise<T> into one returning null of type Void. If this instance completes normally, the returned promise will complete with null, otherwise it will reflect the Error this instance resolves to.

    The returned TKMPromise<T> will be associated with the scheduler current at the time this method is invoked.

    Declaration

    Swift

    public func asVoid() -> TKMPromise<Void>

    Return Value

    this instance converted to Void.

  • Converts this TKMPromise<T> 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 Error this instance resolves to.

    The returned TKMPromise<T> will be associated with the scheduler current at the time this method is invoked.

    Declaration

    Swift

    public func asConst<TConvert>(_ value: TConvert?) -> TKMPromise<TConvert>

    Return Value

    this instance converted to the given value.

  • Concludes an async flow. This function should be called on TKMPromise<T>s 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 Error it resolves to would get lost. A call to this function ensures, any error that hasn’t been handled is treated as unhandled exception.

    Declaration

    Swift

    public func conclude()
  • 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 TKMPromise<T> to a TKMRuntimeError.cancellationError. 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 TKMPromise<T> will be associated with the scheduler current at the time this method is invoked.

    Declaration

    Swift

    public func cancelable(cancellationToken: TKMCancellationToken, forceImmediately: Bool) -> TKMPromise<T>

    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.

    Return Value

    A promise that is set to a TKMRuntimeError.cancellationError if the passed CancellationToken is cancelled.

  • Undocumented

    Declaration

    Swift

    public func toTKObjcPromise() -> TKObjcPromise