[英]How to send Kotlin Flow events into existing Flow stream via combine?
我有兩個流程。
flow1()
發出一個整數的 stream 。
當單擊按鈕時, flow2()
會發出 integer 。
兩個流都與 combineFlows combinedFlows()
組合,組合結果在textView
中收集和輸出。
問題:當我點擊button
時,textview 沒有更新 flow2 點擊計數。 由於某種原因, combine{ }
運算符在點擊時未收集flow2()
。 如何將flow2()
到現有流 stream 並在文本視圖中收集結果?
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
CoroutineScope(Dispatchers.Main).launch {
combineFlows().collect {
binding.textView.text = "flow1: ${it.first} and flow2 click count: ${it.second}"
}
}
binding.button.setOnClickListener {
CoroutineScope(Dispatchers.Main).launch {
flow2().collect()
}
}
}
fun flow1() = (1..1000).asFlow().onEach { delay(1000) }
fun flow2() = flow {
var i = 0
i++
emit("$i")
}
fun combineFlows() = combine(flow1(), flow2()) { a, b -> Pair(a, b) }
}
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="170dp"
android:layout_height="35dp"
android:textSize="11sp"
android:text="Emit Flow"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
</androidx.constraintlayout.widget.ConstraintLayout>
flow {}
builder 是一個冷流,這意味着它在調用終端操作符時執行。 當flow {}
構建器被調用時,它會創建一個Flow
的新實例。 因此,在combine(flow1(), flow2()) { a, b -> Pair(a, b) }
和flow2().collect()
中調用flow2()
兩次將創建兩個不同的Flow
實例。
按鈕點擊應被視為熱流 - 所有收集器都不會獲得所有事件,它們僅接收最后一個事件(或僅接收幾個最后一個事件,具體取決於熱流的配置方式)。
SharedFlow
和StateFlow
是熱流,可以作為用戶用於以下目的:
private val counter = MutableStateFlow(0)
binding.button.setOnClickListener {
counter.update { count -> count + 1 }
}
fun combineFlows() = combine(flow1(), counter) { a, b -> Pair(a, b) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.