简体   繁体   English

如何在 jetpack compose Preview 中显示 Kotlin 协程流数据?

[英]How to show Kotlin coroutine flow data in jetpack compose Preview?

I passed a list of data to a composable function ( data object of type Flow<List<Device>> ).我将数据列表传递给可组合函数( data object of type Flow<List<Device>> )。 I used flow method collectAsState inside composable to use this data as state, and I can see the list in the emulator after building the application.我在可组合内部使用了流方法collectAsState将此数据用作状态,并且我可以在构建应用程序后在模拟器中看到列表。 Mind you, compose preview panel does not show the fake data that I passed to the composable.请注意,撰写预览面板不会显示我传递给可组合的虚假数据

@Preview
@Composable
PreviewHomeScreen() {
  val devices = flow { emit(
    listOf(Device(1, "Device Name 1"), Device(2, "Device Name 2"))
  )}
  HomeScreen(devices)
}

Is there any work that the preview window can show the data of type Flow?预览窗口有没有什么作品可以显示Flow类型的数据?

I can't explain why it doesn't work.我无法解释为什么它不起作用。 That's probably not the purpose of the preview.这可能不是预览的目的。

You should think about separation of concern.您应该考虑关注点分离。 It could be not your Composable responsibility to manage the flow.管理流可能不是您的 Composable 责任。

So just preview the part that don't manage the flow :所以只需预览不管理流程的部分:

@Composable
HomeScreen() {
  val devicesFlow = flow { emit(
    listOf(Device(1, "Device Name 1"), Device(2, "Device Name 2"))
  )}

  val devicesState = devicesFlow.collectAsState(initial = emptyList())

  // HomeScreen recomposed each time flow emit a new list of devices
  HomeScreen(devicesState.value)
}

@Composable
HomeScreen(devices: List<Device>) {
  // Your code here
}

@Preview
@Composable
PreviewHomeScreen() {
  val devices = listOf(Device(1, "Device Name 1"), Device(2, "Device Name 2"))
  HomeScreen(devices)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM