Kotlin Coroutines provide a new way to write asynchronous and concurrent code using suspending functions and structured concurrency. Coroutines avoid callbacks and allow sequencing of asynchronous code using async/await. Coroutines are lightweight threads that can be suspended and resumed. Channels allow coroutines to communicate and share data. Flows provide a reactive streams API for coroutines. Kotlin coroutines offer improvements over other asynchronous programming models like callbacks and RxJava.
As a part of kotlinx.coroutines 1.2 Flow was introduced as a cold asynchronous data stream. How does it work? What we can do with it? Is it that we waiting so long for replacing Rx? The talk has answers to them.
This is an introduction to Kotlin Coroutines and How we can use it in Android. I have tried cover all the basic stuff of coroutine and also added a comparison of thread and coroutine. Github sample project link: https://github.com/bipinvaylu/kotlin-coroutines
Slides with speaker contents: https://docs.google.com/presentation/d/1Wn9ImL9meON2Ohg7pPVYCXKNezilJyX6ewDWU3ljrwE/edit?usp=sharing
Utilizing Kotlin Flows in an Android application
Vijay will be revealing to you the kind of challenges we face while working with asynchronous data streams and how Kotlin Flows solves them.
Learn the latest tips, tricks, and tools for Android Development from our international team of Android Developers in Bangkok!
As a part of kotlinx.coroutines 1.2 Flow was introduced as a cold asynchronous data stream. How does it work? What we can do with it? Is it that we waiting so long for replacing Rx? The talk has answers to them.
This is an introduction to Kotlin Coroutines and How we can use it in Android. I have tried cover all the basic stuff of coroutine and also added a comparison of thread and coroutine. Github sample project link: https://github.com/bipinvaylu/kotlin-coroutines
Slides with speaker contents: https://docs.google.com/presentation/d/1Wn9ImL9meON2Ohg7pPVYCXKNezilJyX6ewDWU3ljrwE/edit?usp=sharing
Utilizing Kotlin Flows in an Android application
Vijay will be revealing to you the kind of challenges we face while working with asynchronous data streams and how Kotlin Flows solves them.
Learn the latest tips, tricks, and tools for Android Development from our international team of Android Developers in Bangkok!
Improving app performance with Kotlin CoroutinesHassan Abid
Coroutines were added to Kotlin in version 1.3 and since then they became a popular choice for android developers to simplify code that executes asynchronously. Coroutines are lightweight threads and on android they help to solve the primary problems of long running tasks that might block the main thread and also providing safety for offloading network or disk operations from the main thread. This talk covers how coroutines work with architecture components
In this tutorial on What are Coroutines in Kotlin, you will learn the basics of threads and understand how coroutines work in Kotlin. You'll look at the different features and examples of coroutines. Finally, you'll see a demo of Kotlin Coroutines.
Kotlin Coroutines and Android sitting in a treeKai Koenig
Since the release of Kotlin 1.1 there is now the new language feature of Kotlin Coroutines available for use in Java and Android projects. Coroutines are a new way to write asynchronous and non-blocking code. They can be thought of as light-weight threads without having to deal with all the problems that threads bring to the table.
A lot of developers think that Kotlin Coroutines are mainly or only useful for Kotlin on the JVM, but that’s not true. There are a variety of use cases in which the application of Coroutines can make a lot of sense on Android.
This talk is introducing the ideas behind Kotlin Coroutines, showing how to use them in Kotlin code for both the JVM and Android via the kotlinx-coroutines APIs and then exploring specific applications in Android. Part of this is a deeper look into the use of Coroutines in higher-level frameworks such as AsyncAwait and Anko.
AngularJS $http Interceptors (Explanation and Examples)Brian Swartzfager
Slide deck from a 10-minute lightning talk on AngularJS $http interceptors (what they are, how to write them, and what you can use them for) presented at the AngularJS Meetup hosted by Difference Engine in Washington DC on Feb. 18, 2015.
All about asynchronous programming from .NET starting from initial framework to latest version. We will be looking into almost all features from .NET which are related to Asynchronous Programming. This seminar will cover up evolution of asynchronous programming and slowly moving to Task.
Async/await and the Task model are the main features of C# 5/.NET 4.5. While asynchronous programming can be done in most languages, all have different specifics, usage and trade-offs. You will see, in this presentation, what is the asynchronous Task model in .NET and why it matters for web apps.
Go is a language developed by Google with multi-core in mind. Differ from other languages, concurrency is a first-class primitive in Go. This talk covers some useful patterns for dealing with concurrency.
Kotlin coroutine - the next step for RxJava developer?Artur Latoszewski
Kotlin is a language that is rapidly gaining popularity, among others thanks to cooperation with Java. On the other hand, RxJava has brought us many solutions to problems related to asynchronous code. If everything is so cool, do we need anything else in the Kotlin world? Is Kotlin Coroutine a competition for RxJava?
droidcon Transylvania - Kotlin CoroutinesArthur Nagy
We face challenges with threading on a daily basis. There are too many ways to do it, too many options. Do I use an AsyncTaks, a Runnable or RxJava, what do I do? All these available APIs lead to an almost inevitable callback hell.
This talk will introduce Kotlin Coroutines as an alternative solution to this problem. We’re going to explore simple ways to perform long-running tasks and computation heavy operations in an asynchronous way, without freezing or crashing your app, while keeping the code clean and readable at the same time.
Improving app performance with Kotlin CoroutinesHassan Abid
Coroutines were added to Kotlin in version 1.3 and since then they became a popular choice for android developers to simplify code that executes asynchronously. Coroutines are lightweight threads and on android they help to solve the primary problems of long running tasks that might block the main thread and also providing safety for offloading network or disk operations from the main thread. This talk covers how coroutines work with architecture components
In this tutorial on What are Coroutines in Kotlin, you will learn the basics of threads and understand how coroutines work in Kotlin. You'll look at the different features and examples of coroutines. Finally, you'll see a demo of Kotlin Coroutines.
Kotlin Coroutines and Android sitting in a treeKai Koenig
Since the release of Kotlin 1.1 there is now the new language feature of Kotlin Coroutines available for use in Java and Android projects. Coroutines are a new way to write asynchronous and non-blocking code. They can be thought of as light-weight threads without having to deal with all the problems that threads bring to the table.
A lot of developers think that Kotlin Coroutines are mainly or only useful for Kotlin on the JVM, but that’s not true. There are a variety of use cases in which the application of Coroutines can make a lot of sense on Android.
This talk is introducing the ideas behind Kotlin Coroutines, showing how to use them in Kotlin code for both the JVM and Android via the kotlinx-coroutines APIs and then exploring specific applications in Android. Part of this is a deeper look into the use of Coroutines in higher-level frameworks such as AsyncAwait and Anko.
AngularJS $http Interceptors (Explanation and Examples)Brian Swartzfager
Slide deck from a 10-minute lightning talk on AngularJS $http interceptors (what they are, how to write them, and what you can use them for) presented at the AngularJS Meetup hosted by Difference Engine in Washington DC on Feb. 18, 2015.
All about asynchronous programming from .NET starting from initial framework to latest version. We will be looking into almost all features from .NET which are related to Asynchronous Programming. This seminar will cover up evolution of asynchronous programming and slowly moving to Task.
Async/await and the Task model are the main features of C# 5/.NET 4.5. While asynchronous programming can be done in most languages, all have different specifics, usage and trade-offs. You will see, in this presentation, what is the asynchronous Task model in .NET and why it matters for web apps.
Go is a language developed by Google with multi-core in mind. Differ from other languages, concurrency is a first-class primitive in Go. This talk covers some useful patterns for dealing with concurrency.
Kotlin coroutine - the next step for RxJava developer?Artur Latoszewski
Kotlin is a language that is rapidly gaining popularity, among others thanks to cooperation with Java. On the other hand, RxJava has brought us many solutions to problems related to asynchronous code. If everything is so cool, do we need anything else in the Kotlin world? Is Kotlin Coroutine a competition for RxJava?
droidcon Transylvania - Kotlin CoroutinesArthur Nagy
We face challenges with threading on a daily basis. There are too many ways to do it, too many options. Do I use an AsyncTaks, a Runnable or RxJava, what do I do? All these available APIs lead to an almost inevitable callback hell.
This talk will introduce Kotlin Coroutines as an alternative solution to this problem. We’re going to explore simple ways to perform long-running tasks and computation heavy operations in an asynchronous way, without freezing or crashing your app, while keeping the code clean and readable at the same time.
Aplicações assíncronas no Android com Coroutines & JetpackNelson Glauber Leal
Para usufruir dos múltiplos núcleos existentes nos processadores dos smartphones atuais, podemos realizar chamadas assíncronas de modo a paralelizar o fluxo de execução da aplicação. Normalmente isso é feito por meio de threads e callbacks que acabam por adicionar uma complexidade ao código que pode comprometer sua leitura e manutenção. Nessa apresentação, veremos como utilizar a API de Coroutines do Kotlin em conjunto com diversas bibliotecas do Jetpack do Android de modo a implementar programação assíncrona forma simples e eficiente.
Aplicações Assíncronas no Android com Coroutines e JetpackNelson Glauber Leal
Para usufruir dos múltiplos núcleos existentes nos processadores dos smartphones atuais, podemos realizar chamadas assíncronas de modo a paralelizar o fluxo de execução da aplicação. Normalmente isso é feito por meio de threads e callbacks que acabam por adicionar uma complexidade ao código que pode comprometer sua leitura e manutenção. Nessa apresentação, veremos como utilizar a API de Coroutines do Kotlin em conjunto com diversas bibliotecas do Jetpack do Android de modo a implementar programação assíncrona forma simples e eficiente.
Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24Joachim Bengtsson
Nevyn Bengtsson (of Lookback, previously Spotify) presents his take on Futures/Promises/Tasks in Swift, and the problems with not abstracting asychronous code.
Code: https://github.com/nevyn/SPAsync/blob/master/Swift/main.swift
Blog: http://overooped.com/post/41803252527/methods-of-concurrency
Transcript: https://raw.githubusercontent.com/nevyn/SPAsync/master/Meta/SLUG%20Lightning%202015%20notes.txt
Slides from my talk at UA Mobile 2017, 2017-11-25
Video: https://www.youtube.com/watch?v=tql9fmWX_oc
Modern programming cannot be imagined without long-running operations such as CPU-intensive computations or blocking IO running in the background. Unfortunately, having too many active threads is very expensive and kills performance, but there's a solution - coroutines. They provide a way to avoid blocking a thread and replace it with a cheaper and more controllable operation: suspension of a coroutine.
I'll talk about generators/yield, async/await, channels, composable/delimited continuations, and its usage; consider available APIs and make the overview of standard kotlinx.coroutines library.
O desenvolvimento de aplicações Android comumente exigem a criação de chamadas assíncronas, que podem acabar gerando diversos problemas como por exemplo o famigerado callback hell. As Coroutines oferecem uma maneira de escrever códigos assíncronos de forma sequencial em uma co-rotina, possibilitando um código mais compacto, fácil de gerenciar e alterar, além de gerar as chamadas lightweight threads, muito mais performáticas que as threads comuns. Nessa palestra vamos mostrar as principais features do Coroutines que podem resolver esse tipo de problema.
NDC Sydney 2019 - Async Demystified -- Karel ZikmundKarel Zikmund
NDC Sydney 2019 conference in Sydney, AU - 2019/10/15
Talk: War stories from .NET team by Karel Zikmund
https://sessionize.com/s/karel-zikmund/async-demystified/24175
https://www.youtube.com/watch?v=TgUYcZV-foM
비행기 설계를 왜 통일 해야 할까?
디자인 시스템을 하는 이유
비행기들이 다 용도가 다르다...어떻게 설계하지?
맥락이 다른 페이지와 패턴
경유지까지 아직 멀었다... 언제 수리하지?
디자인 시스템을 적용하는 시점
엔지니어랑 얘기해서 정비해야하는데...어떻게 수리하지?
디자인 시스템을 적용하는 프로세스
비행기 설계가 바뀐걸 어떻게 알리지?
디자인 시스템의 전파
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
13. Example: simple consecutive logic
Use authentication service:
fun login(email: String): UserId
Send a request to a remote data base:
fun load(id: UserId): User
Show the results:
fun show(user: User)
14. Example: simple consecutive logic
fun login(email: String): UserId
fun load(id: UserId): User
fun show(user: User)
fun showUser(email: String) {
val id = login(email)
val user = load(id)
show(user)
} Simple, but wrong…
15. Rewrite with CompletableFuture
fun login(email: String): CompletableFuture<UserId>
fun load(id: UserId): CompletableFuture<User>
fun show(user: User)
fun showUser(email: String) {
login(email)
.thenCompose { load(it) }
.thenAccept { show(it) }
}
Looks complicated…
16. Rewrite with RxJava
fun login(email: String): Single<UserId>
fun load(id: UserId): Single<User>
fun show(user: User)
fun showUser(email: String) {
login(email)
.flatMap { load(it) }
.doOnSuccess { show(it) }
.subscribe()
}
Looks even more complicated…
17. Using async/await in Kotlin
fun login(email: String): Deferred<UserId>
fun load(id: UserId): Deferred<User>
fun show(user: User)
fun showUser(email: String) = async {
val id = login(email).await()
val user = load(id).await()
show(user)
}
runs the code asynchronously
awaits the result of the
asynchronous computation
18. Using async/await in Kotlin
fun login(email: String): Deferred<UserId>
fun load(id: UserId): Deferred<User>
fun show(user: User)
fun showUser(email: String) = async {
val id = login(email).await()
val user = load(id).await()
show(user)
}
Looks better…
19. Rewrite with suspend functions
suspend fun login(email: String): UserId
suspend fun load(id: UserId): User
fun show(user: User)
suspend fun showUser(email: String) {
val id = login(email)
val user = load(id)
show(user)
}
Looks exactly like the initial code!
21. fun test(email: String) {
showUser(email)
}
Error: Suspend function 'showUser'
should be called only from a coroutine
or another suspend function
Q: Where can I call suspend functions?
22. Q: Where can I call suspend functions?
A: Inside coroutines and other suspend functions.
30. Q: How to create a coroutine?
A: Use of so-called “coroutine builders”.
31. - Library functions
- To start a new computation asynchronously:
async { … }
- To start a new computation in a blocking way (often an entry-point):
runBlocking { … }
Coroutine builders
32. fun processImage() = async {
val image = loadImageAsync().await()
setImage(image)
}
fun loadImageAsync() = async {
/* do the work */
}
Simple “load image” example
33. async creates a new coroutine:
starts a new asynchronous computation
fun loadImageAsync() = async {
/* do the work */
}
loadImageAsync
35. fun loadImageAsync(): Deferred<Image> = async {
/* do the work */
}
interface Deferred<out T> {
suspend fun await(): T
}
await is defined as a suspend function
40. Coroutine can have many suspension points
suspend fun showUser(email: String) {
val id = login(email)
val user = load(id)
show(user)
}
suspended: login() load()
41. Suspension points
suspend fun showUser(email: String) {
val id = login(email)
val user = load(id)
show(user)
}
calls of other suspend functions
42. Q: Which coroutine gets suspended when a
suspend function is called?
A: The one that contains this suspend function.
44. Call stack of a coroutine
async
showUser
loadUser
await / library call
suspendCoroutine
suspendCoroutine call
is the language
mechanism to suspend
a given coroutine
45. Call stack of a coroutine
async
showUser
loadUser
await / library call
suspendCoroutine
application layer
library layer
language support
46. Suspended coroutine
async
showUser
loadUser
await / library call
suspendCoroutine
- suspended coroutine is
stored on the heap
- the call stack and values
of all the local variables
are saved
- only one object is used
to store a coroutine
48. suspend fun foo(): Int
suspend fun foo(continuation: Continuation<Int>): Int
“Callbacks” under the hood
Continuation is a generic callback interface:
interface Continuation<in T> {
val context: CoroutineContext
fun resume(value: T)
fun resumeWithException(exception: Throwable)
}
Each suspend function has a hidden parameter:
49. Q: On which thread does the coroutine
resume?
A: You specify that.
50. Run new or resumed coroutine on a thread from the thread pool:
async(Dispatchers.Default) { ... }
Run new or resumed coroutine on the main thread:
async(Dispatchers.Main) { ... }
…
Specify the context
51. Run Schedule new or resumed coroutine on a thread from the thread
pool:
async(Dispatchers.Default) { ... }
Run Schedule new or resumed coroutine on the main thread:
async(Dispatchers.Main) { ... }
…
Specify the context
55. fun overlay(image1: Image, image2: Image): Image
suspend fun loadAndOverlay() {
val first = async { loadImage("green") }
val second = async { loadImage("red") }
return overlay(first.await(), second.await())
}
Two asynchronous coroutines
loadAndOverlay
loadImage
loadImage
56. Q: What happens if an exception is thrown
inside the first child coroutine (during an image
loading)?
A: The second coroutine leaks!
57. Problem: leaking coroutine
✗
fails
leaks!!!
✗ fails
fun overlay(image1: Image, image2: Image): Image
suspend fun loadAndOverlay() {
val first = async { loadImage("green") }
val second = async { loadImage("red") }
return overlay(first.await(), second.await())
}
58. Solution: introducing local scope
suspend fun loadAndOverlay(): Image =
coroutineScope {
val first = async { loadImage("green") }
val second = async { loadImage("red") }
overlay(first.await(), second.await())
}
✗
fails
catches exception
✗
cancelled
59. suspend fun loadAndOverlay(): Image =
coroutineScope {
val first = async { loadImage("green") }
val second = async { loadImage("red") }
overlay(first.await(), second.await())
}
✗
fails
✗ fails
✗
cancelled
Solution: introducing local scope
60. Coroutine scope
• waits for completion of all the child
coroutines inside this scope
• cancels all the child coroutines if it
gets cancelled (explicitly or by
catching an exception from a child
coroutine)
61. • You can only start a new coroutine inside a scope:
Enforcing structure
coroutineScope {
async { ... }
}
GlobalScope.async { ... }
62. • Each coroutine has the corresponding scope
GlobalScope.async {
// started in the scope of outer coroutine:
this.async { ... }
}
Enforcing structure
70. Send & Receive “views” for the same channel
interface SendChannel<in E> {
suspend fun send(element: E)
fun close()
}
interface ReceiveChannel<out E> {
suspend fun receive(): E
}
interface Channel<E> : SendChannel<E>, ReceiveChannel<E>
72. “Rendezvous” channel semantics
• An element is transferred from sender to receiver only when
send and receive invocations meet in time (“rendezvous”)
• send suspends until another coroutine invokes receive
• receive suspends until another coroutine invokes send
82. send(task2)
Producer-consumer solution
val channel = Channel<Task>()
waiting for “receive” val task =
channel.receive()
processTask(task)
processing task1
channel.send(task1)
channel.send(task2)
channel.close()
83. send(task2)
Producer-consumer solution
val channel = Channel<Task>()
receiveRendezvous!
val task =
channel.receive()
processTask(task)
val task =
channel.receive()
processTask(task)
processing task1
channel.send(task1)
channel.send(task2)
channel.close()
84. Producer-consumer solution
val channel = Channel<Task>()
processing task2
val task =
channel.receive()
processTask(task)
val task =
channel.receive()
processTask(task)
processing task1
channel.send(task1)
channel.send(task2)
channel.close()
85. consumer #1
producer #1
send tasks
receive tasks
consumer #2
Producer-consumer solution: many tasks
val channel = Channel<Task>()
86. Producer-consumer solution: many tasks
val channel = Channel<Task>()
async {
for (i in 1..N) {
channel.send(Task("task$i"))
}
channel.close()
}
producer
87. Producer-consumer solution: many tasks
val channel = Channel<Task>()
...
async { worker(channel) }
async { worker(channel) }
consumer #1
consumer #2
suspend fun worker(channel: Channel<Task>) {
for (task in channel) {
processTask(task)
}
}
calls receive while iterating