Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Coroutines Flow 入門 / Coroutines Flow Introduction

star_zero
August 05, 2019

Coroutines Flow 入門 / Coroutines Flow Introduction

star_zero

August 05, 2019
Tweet

More Decks by star_zero

Other Decks in Programming

Transcript

  1. 基本的なやつ fun main() = runBlocking { val flow = flow

    { repeat(3) { emit(it) } } flow.collect { println(it) } }
  2. 基本的なやつ fun main() = runBlocking { val flow = flow

    { repeat(3) { emit(it) } } flow.collect { println(it) } } Flow builder
  3. 基本的なやつ fun main() = runBlocking { val flow = flow

    { repeat(3) { emit(it) } } flow.collect { println(it) } } 値を送出
  4. 基本的なやつ fun main() = runBlocking { val flow = flow

    { repeat(3) { emit(it) } } flow.collect { println(it) } } 値を受信
  5. Flow builders •Flow { } •flowOf(...) ‣ flowOf(1, 2, 3)

    •(() -> T).asFlow() ‣ ({ 1 }).asFlow()
  6. Flow operators fun main() = runBlocking { val flow =

    flowOf(1, 2, 3, 4, 5) flow.map { it * 2 }.collect { println(it) } } 値を2倍
  7. Flow operators fun main() = runBlocking { val flow =

    flowOf(1, 2, 3, 4, 5) flow.filter { it % 2 == 0 }.collect { println(it) } } 偶数のみ
  8. Terminal operators fun main() = runBlocking { val flow =

    flowOf(1, 2, 3, 4, 5) val value = flow .filter { it == 5 } .single() println(value) // 5 } 複数の値の場合は例外になる
  9. Terminal operators fun main() = runBlocking { val flow =

    flowOf(1, 2, 3, 4, 5) val value = flow .reduce { accumulator, value -> accumulator + value } // 1 + 2 + 3 + 4 + 5 println(value) // 15 }
  10. Terminal operators fun main() = runBlocking { val flow =

    flowOf(1, 2, 3, 4, 5) val value = flow .toList() println(value) // [1, 2, 3, 4, 5] }
  11. Change context fun main() = runBlocking { val flow =

    flowOf(1, 2, 3, 4, 5) flow .map { println("map: ${Thread.currentThread().name}") it + 1 } .flowOn(Dispatchers.IO) .collect { println("collect: ${Thread.currentThread().name}") } } worker main
  12. Change context fun main() = runBlocking { val flow =

    flowOf(1, 2, 3, 4, 5) flow .map { } .flowOn(Dispatchers.IO) .filter { } .flowOn(Dispatchers.Default) .map { } .flowOn(Dispatchers.IO) .collect { } }
  13. Change context fun main() = runBlocking { val flow =

    flowOf(1, 2, 3, 4, 5) flow .map { } .flowOn(Dispatchers.IO) .flowOn(Dispatchers.Default) .collect { } } 最初のやつが優先
  14. Change context fun main() = runBlocking { val flow =

    flow { emit(1) launch { emit(2) } } flow.collect { } } emit時にContextが違うので 例外になる
  15. Exception fun main() = runBlocking { flow { } .map

    { } .catch { } .map { } .catch { } .collect { } } ① ② ③ ③の例外はここで捕捉 ①と②の例外はここで捕捉 それ以降は実行されない
  16. Exception fun main() = runBlocking { flow { emit(1) }.catch

    { emit(-1) }.collect { println(it) } } 例外発生時に別の値を送出
  17. Exception fun main() = runBlocking { flow { } .map

    { } .onCompletion { } .map { } .onCompletion { } .collect { } } finallyみたいなやつ