Share
Embed
Kotlin Coroutines & Android
star_zero
July 21, 2020
Transcript
94 slides
-
Kotlin Coroutines & Android Kenji Abe / @STAR_ZERO Android, Kotlin
GDE Cookpad Inc. -
This class was deprecated in API level 30. Use the
standard java.util.concurrent or Kotlin concurrency utilities instead. AsyncTask -
Title safe Actio n safe Kotlin Coroutines are the recommended
solution for async code. -
fun request(callback: (Data) -> Unit) { // Network access }
fun loadData() { request { data -> show(data) } } Callback -
fun loadData() { request1 { data1 -> request2 { data2
-> request3 { data3 -> request4 { data4 -> request5 { data5 -> // ... } } } } } } Callback -
suspend fun request(): String = withContext(Dispatchers.IO) { // Network access
} suspend fun loadData() { val data = request() show(data) } Coroutines -
suspend fun request(): String = withContext(Dispatchers.IO) { // Network access
} suspend fun loadData() { val data = request() show(data) } Coroutines -
suspend fun request(): String = withContext(Dispatchers.IO) { // Network access
} suspend fun loadData() { val data = request() show(data) } Coroutines -
suspend fun request(): String = withContext(Dispatchers.IO) { // Network access
} suspend fun loadData() { val data = request() show(data) } Coroutines request show Background Thread -
suspend fun request(): String = withContext(Dispatchers.IO) { // Network access
} suspend fun loadData() { val data = request() show(data) } Coroutines request show Background Thread -
suspend fun request(): String = withContext(Dispatchers.IO) { // Network access
} suspend fun loadData() { val data = request() show(data) } Coroutines request show Background Thread 待機 -
suspend fun request(): String = withContext(Dispatchers.IO) { // Network access
} suspend fun loadData() { val data = request() show(data) } Coroutines request show Background Thread -
suspend fun request(): String = withContext(Dispatchers.IO) { // ... }
CoroutineDispatcher -
suspend fun run() { withContext(Dispatchers.IO) { // ... } withContext(Dispatchers.Default)
{ // ... } withContext(Dispatchers.Main) { // ... } } CoroutineDispatcher -
० CoroutineScope ◦ Coroutineのライフサイクルの管理 ◦ キャンセルや例外処理の対応 ० CoroutineBuilder ◦ 新しくCoroutineを作成して実行する
◦ launch / async CoroutineScope / CoroutineBuilder -
fun event() { request() } suspend fun request() { //
... } CoroutineScope / CoroutineBuilder -
fun event() { request() } suspend fun request() { //
... } CoroutineScope / CoroutineBuilder Suspend function 'request' should be called only from a coroutine or another suspend function -
val scope = CoroutineScope(Dispatchers.Main) fun event() { scope.launch { request()
} } CoroutineScope / CoroutineBuilder -
val scope = CoroutineScope(Dispatchers.Main) fun event() { scope.launch { request()
} } CoroutineScope / CoroutineBuilder CoroutineScope 作成 -
val scope = CoroutineScope(Dispatchers.Main) fun event() { scope.launch { request()
} } CoroutineScope / CoroutineBuilder Coroutine 作成 -
val job = scope.launch { request() } // ... job.cancel()
// or scope.cancel() Cancellation -
val job = scope.launch { while(true) { // ... println("Hello")
} } // ... job.cancel() Cancellation -
val job = scope.launch { while(true) { // ... println("Hello")
} } // ... job.cancel() Cancellation Hello Hello Hello Hello Hello Hello . . -
val job = scope.launch { while(isActive) { // ... println("Hello")
} } // ... job.cancel() Cancellation キャンセルされているか確認 -
val job = scope.launch { while(isActive) { ensureActive() // ...
println("Hello") } } // ... job.cancel() Cancellation キャンセルされている場合 CancellationException -
suspend fun request(): Data { delay(3000) // ... } val
time = measureTimeMillis { val data1 = request() val data2 = request() } println("time = $time") async / await -
suspend fun request(): Data { delay(3000) // ... } val
time = measureTimeMillis { val data1 = request() val data2 = request() } println("time = $time") async / await 約 6000 ms -
val time = measureTimeMillis { val deferred1 = async {
request() } val deferred2 = async { request() } val data1 = deferred1.await() val data2 = deferred2.await() } println("time = $time") async / await -
val time = measureTimeMillis { val deferred1 = async {
request() } val deferred2 = async { request() } val data1 = deferred1.await() val data2 = deferred2.await() } println("time = $time") async / await 処理開始して待たずに次へ -
val time = measureTimeMillis { val deferred1 = async {
request() } val deferred2 = async { request() } val data1 = deferred1.await() val data2 = deferred2.await() } println("time = $time") async / await 完了を待って結果を返す -
val time = measureTimeMillis { val deferred1 = async {
request() } val deferred2 = async { request() } val data1 = deferred1.await() val data2 = deferred2.await() } println("time = $time") async / await 約 3000 ms -
val handler = CoroutineExceptionHandler { _, throwable -> // ...
} val scope = CoroutineScope(Dispatchers.Default + handler) scope.launch { throw IllegalStateException() } Exception -
val handler = CoroutineExceptionHandler { _, throwable -> // ...
} val scope = CoroutineScope(Dispatchers.Default + handler) scope.launch { throw IllegalStateException() } Exception -
fun createFlow(): Flow<Int> { return flow { (1..10).forEach { emit(it)
} } } scope.launch { val flow = createFlow() flow.collect { println(it) } } Flow -
fun createFlow(): Flow<Int> { return flow { (1..10).forEach { emit(it)
} } } scope.launch { val flow = createFlow() flow.collect { println(it) } } Flow Flowを作成 -
fun createFlow(): Flow<Int> { return flow { (1..10).forEach { emit(it)
} } } scope.launch { val flow = createFlow() flow.collect { println(it) } } Flow Flowはまだ動かない -
fun createFlow(): Flow<Int> { return flow { (1..10).forEach { emit(it)
} } } scope.launch { val flow = createFlow() flow.collect { println(it) } } Flow ここで動きだす -
fun createFlow(): Flow<Int> { return flow { (1..10).forEach { emit(it)
} } } scope.launch { val flow = createFlow() flow.collect { println(it) } } Flow 値を送信 emit された値が通知される -
flow.map { it * it }.filter { it % 3
== 0 }.collect { // ... } Flow -
suspend fun run() = suspendCancellableCoroutine<Response> { continuation -> request(object :
Callback { override fun success(response: Response) { continuation.resume(response) } override fun failure(e: Exception) { continuation.resumeWithException(e) } }) continuation.invokeOnCancellation { cancel() } } suspendCancellableCoroutine -
suspend fun run() = suspendCancellableCoroutine<Response> { continuation -> request(object :
Callback { override fun success(response: Response) { continuation.resume(response) } override fun failure(e: Exception) { continuation.resumeWithException(e) } }) continuation.invokeOnCancellation { cancel() } } suspendCancellableCoroutine -
suspend fun run() = suspendCancellableCoroutine<Response> { continuation -> request(object :
Callback { override fun success(response: Response) { continuation.resume(response) } override fun failure(e: Exception) { continuation.resumeWithException(e) } }) continuation.invokeOnCancellation { cancel() } } suspendCancellableCoroutine suspend funの戻り値 -
suspend fun run() = suspendCancellableCoroutine<Response> { continuation -> request(object :
Callback { override fun success(response: Response) { continuation.resume(response) } override fun failure(e: Exception) { continuation.resumeWithException(e) } }) continuation.invokeOnCancellation { cancel() } } suspendCancellableCoroutine throw Exception -
suspend fun run() = suspendCancellableCoroutine<Response> { continuation -> request(object :
Callback { override fun success(response: Response) { continuation.resume(response) } override fun failure(e: Exception) { continuation.resumeWithException(e) } }) continuation.invokeOnCancellation { cancel() } } suspendCancellableCoroutine Coroutineがキャンセルされた -
fun run() = callbackFlow<Data> { val callback = object :
Callback { override fun onReceive(data: Data) { offer(data) } } registerCallback(callback) awaitClose { unregisterCallback(callback) } } callbackFlow -
fun run() = callbackFlow<Data> { val callback = object :
Callback { override fun onReceive(data: Data) { offer(data) } } registerCallback(callback) awaitClose { unregisterCallback(callback) } } callbackFlow -
fun run() = callbackFlow<Data> { val callback = object :
Callback { override fun onReceive(data: Data) { offer(data) } } registerCallback(callback) awaitClose { unregisterCallback(callback) } } callbackFlow 値を送信 -
fun run() = callbackFlow<Data> { val callback = object :
Callback { override fun onReceive(data: Data) { offer(data) } } registerCallback(callback) awaitClose { unregisterCallback(callback) } } callbackFlow キャンセルされるまで待機 -
@Dao interface UserDao { @Query("SELECT * FROM user") suspend fun
getAll(): List<User> } Room -
@Dao interface UserDao { @Query("SELECT * FROM user") fun getAll():
Flow<List<User>> } Room -
class MyWorker( context: Context, params: WorkerParameters ) : CoroutineWorker(context, params)
{ override suspend fun doWork(): Result { val data = readData() upload(data) return Result.success() } } WorkManager -
lifecycleScope.launch { // ... } lifecycleScope onCreate onPause Cancelled Active
onStart onResume onDestroy onStop init -
lifecycleScope.launchWhenCreated { // ... } lifecycleScope onCreate onPause Cancelled Active
onStart onResume onDestroy onStop init Pause -
lifecycleScope.launchWhenStarted { // ... } lifecycleScope onCreate onPause Cancelled Pause
onStart onResume onDestroy onStop init Active Pause -
lifecycleScope.launchWhenResumed { // ... } lifecycleScope onCreate onPause onStart onResume
onDestroy onStop init Cancelled Pause Active Pause -
val data: LiveData<String> = liveData { // ... emit("test") }
LiveData suspend -
val data = MutableLiveData(0) val flow = data.asFlow() scope.launch {
flow.collect { // ... } } LiveData -
val data = MutableLiveData(0) val flow = data.asFlow() scope.launch {
flow.collect { // ... } } LiveData LiveData → Flow -
val flow = flow { // ... emit("test") } val
liveData = flow.asLiveData() liveData.observe(this) { // ... } LiveData -
val flow = flow { // ... emit("test") } val
liveData = flow.asLiveData() liveData.observe(this) { // ... } LiveData Flow → LiveData -
fun FusedLocationProviderClient.locationFlow() = callbackFlow<Location> { val callback = object :
LocationCallback() { override fun onLocationResult(result: LocationResult?) { result ?: return try { offer(result.lastLocation) } catch(e: Exception) {} } } requestLocationUpdates(/* ... */) .addOnFailureListener { e -> close(e) // in case of exception, close the Flow } // clean up when Flow collection ends awaitClose { removeLocationUpdates(callback) } } asLiveData vs lifecycleScope.launchWhenStarted -
myFlow.asLiveData().observe { // ... } lifecycleScope.launchWhenStarted { myFlow.collect { //
... } } asLiveData vs lifecycleScope.launchWhenStarted -
asLiveData vs lifecycleScope.launchWhenStarted Activity onStart Active Active onStop asLiveData lifecycleScope.launchWhenStarted
Observer: Flow: Active Active Collector: Flow: -
asLiveData vs lifecycleScope.launchWhenStarted Activity onStart Active Active onStop asLiveData lifecycleScope.launchWhenStarted
Cancelled Cancelled Observer: Flow: Observer: Flow: Active Active Paused Active Collector: Flow: Collector: Flow: -
class ViewModel { private val _counter = MutableStateFlow(0) val counter:
StateFlow<Int> = _counter fun increment() { _counter.value++ } } lifecycleScope.launchWhenStarted { viewModel.counter.collect { println(it) } } StateFlow -
MutableLiveData<T>: var value: T fun postValue(value: T) LiveData<T>: val value:
T LiveData vs StateFlow MutableStateFlow<T>: var value: T StateFlow<T>: val value: T -
LiveData vs StateFlow • Data Holder • LifecycleOwner • 同じ値も通知される
• 初期値は通知されない • Transformations • Flow (Hot Stream) • CoroutineScope • 同じ値は通知されない • 初期値も通知 • オペレーター LiveData StateFlow -
Appendix goo.gle/coroutines-posts • Coroutines: First things first • Cancellation in
coroutines • Exceptions in Coroutines • The suspend modifier — Under the hood goo.gle/coroutines-101 • Coroutines 101 codelabs.developers.google.com • Use Kotlin Coroutines in your Android App • Learn advanced coroutines with Kotlin Flow and LiveData • Building a Kotlin extensions library