Await Expressions
In RemObjects C#, await
can also be used with methods that take a "callback" closure as last parameter. The parameters of the closure will turn into return values of the call. For example, consider the following call using Elements RTL's Http
class:
void downloadData()
{
Http.ExecuteRequestAsJson(HttpRequest(URL), (response) => {
if (response.Content != null)
{
dispatch_async(dispatch_get_main_queue( () => {
data = response.Content;
tableView.reloadData();
});
}
});
}
This code uses two nested closures, first to wait for the response of the network request, and then to process its results on the main UI thread. With await
this can be unwrapped nicely:
func downloadData() {
var response = await Http.ExecuteRequestAsJson(HttpRequest(URL)) {
if let content = response.Content
{
await dispatch_async(dispatch_get_main_queue());
data = response.Content;
tableView.reloadData();
}
}
Note how the parameter of the first closure, response
becomes a local variable, and how await
is used without return value on the dispatch_async
call.
For callbacks that return more than one parameter, await
will return a tuple, e.g.:
var (value, error) = await TryToGetValueOrReturnError();
...