这是我尝试使用的 MutableStateFlow 值:
val songList: MutableStateFlow<MutableList<Song>> = MutableStateFlow(arrayListOf())
Run Code Online (Sandbox Code Playgroud)
我需要观察上面 MutableList 上的更改(在 add、removeAt 等方法之后),但无法实现这一点。我的猜测是,因为只有列表的元素发生变化,而不是列表本身发生变化,所以不会触发收集方法。
如果可能的话,如何使用 StateFlow 实现这一目标?如果不是,正确的做法是什么?
请注意,我需要 arrayListOf() 的初始值,因此 LiveData 对我来说可能不够。
android reactive-programming android-livedata kotlin-stateflow
我是 Jetpack Compose 的新手,我正在尝试弄清楚当用户单击 FloatingActionButton 时如何重新组合 LazyColumn 列表。
如图所示,我有一个基本的脚手架布局,其中包含一个用于内容的 LazyColumn。底部是一个 FloatingActionButton。我希望能够单击该 FloatingActionButton,将“Molly”添加到我的姓名列表中,让应用程序重新组合我的列表,并显示包括 Molly 在内的完整列表。代码如下图。
package com.learning.lazylistexample
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import com.learning.lazylistexample.ui.theme.LazyListExampleTheme
import kotlinx.coroutines.launch
data class ListItem(val name: String)
private var listItems: MutableList<ListItem> = mutableListOf(
ListItem("Al"),
ListItem("Barb"),
ListItem("Cheryl"),
ListItem("Dave"),
ListItem("Ed"),
ListItem("Frank"),
ListItem("Gloria"),
ListItem("Henry"),
ListItem("Ingrid"),
ListItem("Jack"),
ListItem("Kayla"),
ListItem("Larry")
)
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent { …Run Code Online (Sandbox Code Playgroud)