Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>>). 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. 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?

like image 482
Ehsan Shadi Avatar asked Aug 01 '21 07:08

Ehsan Shadi


Video Answer


1 Answers

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.

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)
}
like image 139
DamienL Avatar answered Nov 11 '22 10:11

DamienL