使用Jetpack Compose加载数据的一个常见错误(Compose死循环)

  • 原文:Jetpack Compose Load Data (Flow.collectAsState) Common Mistakes (Compose Infinite Loop)
  • 原文地址:Jetpack Compose Load Data (Flow.collectAsState) Common Mistakes (Compose Infinite Loop)
  • 原文发表日期:2021.11.04
  • 原文作者:Desmond Lua
  • 翻译者:tommwq
  • 翻译日期:2023.11.10

下面的数据类用于从firestore数据库加载数据。如果使用flow加载数据,必须确保获取数据的动作仅仅执行一次。

class CardViewModel : ViewModel() {
    val itemsFlow = flow {
      val items = MutableList((1..100).random()) { index ->
          index
      }
      emit(items)
    }
}

添加时间戳来检查数据加载次数。

fun CardScreen(viewModel: CardViewModel = viewModel()) {
    val items by viewModel.itemsFlow.collectAsState(initial = emptyList())
    Text("Items: ${items.size}, Time: ${LocalTime.now()}")
}

如果使用了函数,compose将进入死循环(时间戳将不断持续更新)。

class CardViewModel : ViewModel() {
    private val db = Firebase.firestore
    fun getItems() = flow {
      val items = MutableList((1..100).random()) { index ->
          index
      }
      emit(items)
    }
}
fun CardScreen(viewModel: CardViewModel = viewModel()) {
    val items by viewModel.getItems().collectAsState(initial = emptyList())
    Text("Items: ${items.size}, Time: ${LocalTime.now()}")
}

如果需要使用函数,必须在LaunchedEffect中调用函数。

fun CardScreen(viewModel: CardViewModel = viewModel()) {
    var items by remember { mutableStateOf>( emptyList()) }
    LaunchedEffect(true) { // only launch once
        viewModel.getItems().collect { 
            items = it
        }
    }
    Text("Items: ${items.size}, Time: ${LocalTime.now()}")
}

如果需要加载初始数据,并在每次点击按钮时加载数据:

fun CardScreen(viewModel: CardViewModel = viewModel()) {
    var refreshCount by remember { mutableStateOf(0) }
    var items by remember { mutableStateOf>( emptyList()) }
    LaunchedEffect(refreshCount) { // run if refreshCount is updated
        // you can choose to generate items based on refreshCount
        viewModel.getItems().collect {
            items = it
        }
    }
    // button click will 
    Button(onClick = { refreshCount += 1 }) {
        Text("Refresh")
    }
    Text("Items: ${items.size}, Time: ${LocalTime.now()}")
}

Date: 2023年11月10日

Created: 2023-11-10 周五 23:10

你可能感兴趣的:(翻译,Android)