-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoroutine.html
More file actions
227 lines (203 loc) · 11.1 KB
/
coroutine.html
File metadata and controls
227 lines (203 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
<!DOCTYPE html>
<html lang="en">
<head>
<title>Class Kotlin</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Merriweather+Sans:400,300,700" type="text/css">
<link rel="stylesheet" href="static/app.css" type="text/css">
<link rel="shortcut icon" href="static/logo.png" />
<meta name="theme-color" content="#111111">
<meta name="og:type" content="website">
<meta name="og:title" content="MoraSoftware.github.io">
<meta name="og:description" content="Mora Software">
<meta name="og:site_name" content="Mora Software">
<meta name="og:url" content="{{ site.url }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="block">
<form action="index.html">
<input type="image" src="static/white.jpg" />
</form>
</div>
<div class="block">
<h2>COROUTINES</h2>
</div>
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#init">Scope</a></li>
<li><a data-toggle="tab" href="#builders">Builders</a></li>
<li><a data-toggle="tab" href="#dispatchers">Dispatchers</a></li>
<li><a data-toggle="tab" href="#code">Code</a></li>
</ul>
<div class="tab-content">
<div id="init" class="tab-pane fade in active">
<h3>CoroutineScope</h3>
<p></p>
<p>Allows objects to provide scope for coroutines </p>
<p>async & launch become instance methods</p>
<p>they provide a default context</p>
<p>To start coroutine scope you can:</p>
<p>Use GlobalScope that has empty coroutine context.</p>
<p>Implement CoroutineScope interface. Create a scope from a context:</p>
<xmp>with(CoroutineScope(context = context)){}))</xmp>
<p></p>
<p></p>
<ul class="list-inline">
<li>
<a href="https://blog.kotlin-academy.com/kotlin-coroutines-cheat-sheet-8cf1e284dc35">Reference</a></li>
<li>
<a href="https://github.com/googlecodelabs/kotlin-coroutines">GitHub Google Codelabs</a>
</li>
<li>
<a href="https://www.youtube.com/watch?v=jYuK1qzFrJg"><img src="static/youtube.png"></a>
</li>
<li>
<a href="https://www.youtube.com/watch?v=EOjq4OIWKqM"><img src="static/youtube.png"></a>
</li>
</ul>
</div>
<div id="builders" class="tab-pane fade">
<h3>Coroutine builders</h3>
<p></p>
<p> - launch</p>
<p>Launches new coroutine without blocking current thread and returns a reference to </p>
<p> the coroutine as a Job.</p>
<p>(launch is when you want to fire and forget)</p>
<p></p>
<p> - runBlocking</p>
<p>Runs new coroutine and blocks current theread interruptible until its completion.</p>
<p></p>
<p> - async</p>
<p>Creates new coroutine and returns its future result as an implementation of Deferred.</p>
<p>async doesn't throw until await() o join()</p>
<p>(async is when we wnat to run something, then await the resul)</p>
<p></p>
<p> - withContext</p>
<p>Change a coroutine context for some block.</p>
<p></p>
<p></p>
<a href="https://blog.kotlin-academy.com/kotlin-coroutines-cheat-sheet-8cf1e284dc35">Reference</a>
<a href="https://www.youtube.com/watch?v=jYuK1qzFrJg"><img src="static/youtube.png"></a>
<a href="https://www.youtube.com/watch?v=EOjq4OIWKqM"><img src="static/youtube.png"></a>
</div>
<div id="dispatchers" class="tab-pane fade">
<h3>Coroutine dispatchers</h3>
<p>The things wihich runs and schedules coroutines</p>
<p></p>
<p> - Dispatchers.Default</p>
<p>Different thread(if possible) it is backerd by a shared pool of threads on JVM.</p>
<p>Uses cpuCount threads(core)</p>
<p>Elastic thread executor</p>
<p>Default dispatcher</p>
<p></p>
<p> - Dispatchers.Main</p>
<p>Platform specific main thread (if exists).</p>
<p>Allows running coroutines on UI main thread</p>
<p></p>
<p> - Dispatchers.IO</p>
<p>Thread designed for offloadin blocking IO tasks to a shared pool of threads.</p>
<p>IO dispatcher uses Dispatchers.Default</p>
<p>Designed for blocking I/O tasks</p>
<p></p>
<p> - Dispatchers.Unconfined</p>
<p>Always uses first available thread (most performant dispatcher).</p>
<p></p>
<p> - newSingleThreadContext</p>
<p>Creates a new coroutine execution context using a single thread with built-in yield support</p>
<p></p>
<p></p>
<a href="https://blog.kotlin-academy.com/kotlin-coroutines-cheat-sheet-8cf1e284dc35">Reference</a>
<a href="https://proandroiddev.com/demystifying-coroutinecontext-1ce5b68407ad">Reference</a>
<a href="https://www.youtube.com/watch?v=jYuK1qzFrJg"><img src="static/youtube.png"></a>
<a href="https://www.youtube.com/watch?v=EOjq4OIWKqM"><img src="static/youtube.png"></a>
</div>
<div id="code" class="tab-pane fade">
<h3>Resume with code</h3>
<xmp>
import kotlinx.coroutines.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
fun main(args: Array<String>) {
exampleWithContext()
}
suspend fun printlnDelayed(message: String) {
// Complex calculation
delay(1000)
println(message)
}
suspend fun calculateHardThings(startNum: Int): Int {
delay(1000)
return startNum * 10
}
fun exampleBlocking() = runBlocking {
println("one")
printlnDelayed("two")
println("three")
}
// Running on another thread but still blocking the main thread
fun exampleBlockingDispatcher(){
runBlocking(Dispatchers.Default) {
println("one - from thread ${Thread.currentThread().name}")
printlnDelayed("two - from thread ${Thread.currentThread().name}")
}
// Outside of runBlocking to show that it's running in the blocked main thread
println("three - from thread ${Thread.currentThread().name}")
// It still runs only after the runBlocking is fully executed.
}
fun exampleLaunchGlobal() = runBlocking {
println("one - from thread ${Thread.currentThread().name}")
GlobalScope.launch {
printlnDelayed("two - from thread ${Thread.currentThread().name}")
}
println("three - from thread ${Thread.currentThread().name}")
delay(3000)
}
fun exampleLaunchGlobalWaiting() = runBlocking {
println("one - from thread ${Thread.currentThread().name}")
val job = GlobalScope.launch {
printlnDelayed("two - from thread ${Thread.currentThread().name}")
}
println("three - from thread ${Thread.currentThread().name}")
job.join()
}
fun exampleLaunchCoroutineScope() = runBlocking {
println("one - from thread ${Thread.currentThread().name}")
val customDispatcher = Executors.newFixedThreadPool(2).asCoroutineDispatcher()
launch(customDispatcher) {
printlnDelayed("two - from thread ${Thread.currentThread().name}")
}
println("three - from thread ${Thread.currentThread().name}")
(customDispatcher.executor as ExecutorService).shutdown()
}
fun exampleAsyncAwait() = runBlocking {
val startTime = System.currentTimeMillis()
val deferred1 = async { calculateHardThings(10) }
val deferred2 = async { calculateHardThings(20) }
val deferred3 = async { calculateHardThings(30) }
val sum = deferred1.await() + deferred2.await() + deferred3.await()
println("async/await result = $sum")
val endTime = System.currentTimeMillis()
println("Time taken: ${endTime - startTime}")
}
fun exampleWithContext() = runBlocking {
val startTime = System.currentTimeMillis()
val result1 = withContext(Dispatchers.Default) { calculateHardThings(10) }
val result2 = withContext(Dispatchers.Default) { calculateHardThings(20) }
val result3 = withContext(Dispatchers.Default) { calculateHardThings(30) }
val sum = result1 + result2 + result3
println("async/await result = $sum")
val endTime = System.currentTimeMillis()
println("Time taken: ${endTime - startTime}")
}
</xmp>
<a href="https://www.youtube.com/watch?v=jYuK1qzFrJg"><img src="static/youtube.png"></a>
</div>
</div>
</div>
</body>
</html>