Skip to content

Instantly share code, notes, and snippets.

@hidakatsuya
Last active November 20, 2023 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hidakatsuya/de3cb21b3c3f305370532c4647389281 to your computer and use it in GitHub Desktop.
Save hidakatsuya/de3cb21b3c3f305370532c4647389281 to your computer and use it in GitHub Desktop.
Kotlin Flow

Kotlin Flow について

flow.kt

run2() の結果

1+2=3
2+4=6
3+6=9
4+8=12
5+10=15
6+12=18
7+14=21
8+16=24
9+18=27
10+20=30

run1() の結果

1a
2a
2b
2c

Kotlin Playground https://pl.kotl.in/B2FmDSr_j

説明

Flowcombineは、複数のFlowから値を組み合わせて新しい値を生成するための便利なメソッドです。これにより、複数の非同期なデータストリームを1つにまとめることができます。

combineメソッドは、2つのFlowを受け取り、それらの値が更新されるたびに指定された変換関数を実行し、新しい値を生成します。以下は、基本的な使い方です:

import kotlinx.coroutines.flow.*

fun main() {
    val flow1 = flowOf(1, 2, 3)
    val flow2 = flowOf("A", "B", "C")

    val combinedFlow = flow1.combine(flow2) { value1, value2 ->
        "$value1 - $value2"
    }

    // Collect and print the combined values
    combinedFlow.collect { combinedValue ->
        println(combinedValue)
    }
}

この例では、flow1flow2があります。combineメソッドはこれら2つのFlowを受け取り、新しい値を生成するためのラムダ式を提供します。ここでは、整数と文字列を組み合わせて新しい文字列を生成しています。

実際に実行すると、以下のような出力が得られます:

1 - A
2 - B
3 - C

これにより、2つの異なるFlowの値を組み合わせて新しいFlowを作成することができます。この結果をコレクトすることで、新しい値を受け取ることができます。

参考

https://zenn.dev/yagiryuuu/articles/82b23f85f9258f

import kotlinx.coroutines.flow.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
fun main() {
runBlocking {
run1()
}
runBlocking {
run2()
}
}
suspend fun run1() {
val flow = flowOf(1, 2).onEach { delay(90) }
val flow2 = flowOf("a", "b", "c").onEach { delay(100) }
combine(flow, flow2) {i, s ->
i.toString() + s
}.collect {
println(it)
}
}
suspend fun run2() {
val flow1 = flow {
for (i in 1..10) {
emit(i)
}
}
val flow2 = flow {
for (i in 1..10) {
emit(i * 2)
}
}
combine(flow1, flow2) { a,b ->
print("${a}+${b}=")
a + b
}.collect {
println(it)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment