18. ASYNC / AWAIT - a syntax sugar 🍬🍭🍩
async function downloadAndParse() {
$response = await download();
return json_decode($response)
}
19. ASYNC / AWAIT - wrapping callbacks 🍬🍭🍩
async function sleep(miliseconds) {
return new Promise(function(resolve) {
setTimeout(()=>{resolve()}, miliseconds)
});
}
(async () => {
await sleep(2000);
// do something
})()
20. ASYNC / AWAIT - a syntax sugar 🍬🍭🍩
- Awaitnout funkci mohu spustit pouze z jiné async funkce
nebo async scope
- Async scope:
C#: async main(), async UI events
JS: (async () => { … })() - top-level funkce co nikdy
nerejectuje; nebo pouzit API z Promise
Kotlin: async main(), coroutine launchers
21. ASYNC / AWAIT - C# - task it all 💻💻💻
- Async funkce vrací Task<T>
- ± Promise instance
- await rozbalí
22. ASYNC / AWAIT - C# - wrap a callback
public Task<HttpResponse> LoadHtmlAsync(string url)
{
var task = new TaskCompletionSource<HttpResponse>();
LoadHtml(url, result => { task.SetResult(result); });
return task.Task;
}
23. C#: So, we are ready to … or?
● Cancellation
● Task allocation
● Thread switching
24. C# ASYNC: cancellation
void Autocomplete(text: string) {
// cancel previous search task
var searchTask = SearchAsync(text);
var result = await searchTask;
// process result
}
25. C# ASYNC: cancellation
private CancellationTokenSource? cts = null
void Autocomplete(text: string) {
cts?.Cancel()
cts = new CancellationTokenSource();
try {
var result = await SearchAsync(text, cts.Token);
// process result
} catch (OperationCanceledException) {
} finally { cts?.Dispose() }
}
33. How it works - internally
https://www.markopapic.com/csharp-under-the-hood-async-await/
34. static async Task BarAsync()
{
Console.WriteLine("This happens before await");
int i = await QuxAsync();
Console.WriteLine("This happens after await. The result of
await is " + i);
}
38. if (num1 != 0)
{
Console.WriteLine("This happens before await");
awaiter = Program.QuxAsync().GetAwaiter();
if (!awaiter.IsCompleted){
…
return;
}
}else{
awaiter = this.<>u__1;
this.<>u__1 = new TaskAwaiter<int>();
this.<>1__state = num2 = -1;
}
Console.WriteLine("This happens after await. The result of
await is " + (object) awaiter.GetResult());
40. Kotlin & Coroutines
suspend fun download(): HttpResponse {
}
suspend fun myFun() {
val response = download()
}
41. Kotlin & Coroutines
fun download(c: Continuation<HttpResponse>): HttpResponse {
}
interface Continuation<in T> {
val context: CoroutineContext
fun resume(value: T)
fun resumeWithException(exception: Throwable)
}
42. Kotlin & Coroutines
suspend fun search(test: String): HttpResponse {
}
private var job: Job? = null
fun autocomplete(text: String) {
job?.cancel()
job = GlobalScope.launch(Dispatchers.IO) {
val response = download(text: String)
...
}
}
43. Kotlin & Coroutines
fun search(test: String): Deferred<HttpResponse> {
}
private var job: Job? = null
fun autocomplete(text: String) {
job?.cancel()
job = GlobalScope.launch(Dispatchers.IO) {
val response = download(text: String).await()
...
}
}
44. Kotlin & Coroutines
val jobs = mutableListOf<Deferred<Int>>()
for (i in 0..1_000_000) {
jobs += GlobalScope.async(Dispatchers.Default) {
i + 1
}
}
val nums = jobs.map { it.await() }
https://pl.kotl.in/sf0502yYI