InterruptiblePromise
Promises represent the eventual completion of an asynchronous operation.
A promise has one of three states, PromiseState
, which can be obtained with InterruptiblePromise
:
PromiseState.Pending
- The operation is still pending. The result of the operation isn't available yet.PromiseState.Done
- The operation is complete, and a result is available.PromiseState.Cancelled
- The operation has been cancelled.
An InterruptiblePromise
starts in the PromiseState.Pending
state and transitions to PromiseState.Done
upon completion. If the Promise is cancelled using InterruptiblePromise
, then its state may become PromiseState.Cancelled
(see cancelling a Promise for caveats).
Obtaining results from a Promise
There are two ways of obtaining results from an InterruptiblePromise
:
Polling a Promise
When the InterruptiblePromise
is created, its PromiseState
is set to PromiseState.Pending
. You may poll the future using InterruptiblePromise
to query the state of the asynchronous operation. When its state is PromiseState.Done
, you may obtain the operation's result using InterruptiblePromise
.
Use a Unity Coroutine
Promises use a
CustomYieldInstruction
to facilitate Unity coroutines. Use yield return promiseInstance
to pause execution of your coroutine. Unity will resume execution of your coroutine when InterruptiblePromise
is no longer PromiseState.Pending
.
public void CreatePromise()
{
ResolveAnchorOnRooftopPromise rooftopPromise =
AnchorManager.ResolveAnchorOnRooftopAsync(...);
StartCoroutine(CheckRooftopPromise(rooftopPromise));
}
private IEnumerator CheckRooftopPromise(ResolveAnchorOnTerrainPromise promise)
{
yield return promise;
if (promise.State == PromiseState.Cancelled) yield break;
var result = promise.Result;
/// Use the result of your promise here.
}
Cancelling a Promise
You can try to cancel an InterruptiblePromise
by calling InterruptiblePromise
. Due to multi-threading, it is possible that the cancel operation is not successful, and any Unity coroutine may successfully resume execution regardless.
Details | |||
---|---|---|---|
Template Parameters |
|
Summary
Inheritance
Inherits from:UnityEngine::CustomYieldInstruction
Properties |
|
---|---|
Result
|
T
Gets the result, if the operation is done.
|
State
|
Gets the
PromiseState associated with this promise. |
Public functions |
|
---|---|
Cancel()
|
void
Cancels execution of this promise if it's still pending.
|
Properties
Result
T Result
Gets the result, if the operation is done.
State
PromiseState State
Gets the PromiseState
associated with this promise.
Used to determine if the promise is still waiting for the result.
Public functions
Cancel
void Cancel()
Cancels execution of this promise if it's still pending.