Hi what is the design pattern to have a list of cl...
# compose-web
a
Hi what is the design pattern to have a list of classes containing data which is got from a Promise ? Like how do I set the variable and how do I say that if it's empty, try to get the value and wait until the list has data to put the composables using the data ?
d
You can use the
.await()
extension on the promise to turn it into a coroutine, and then you can treat it like you would treat any data coming from an ordinary coroutine.
a
And what is the design pattern for data coming from a coroutine ? :>
d
If you wanted to work directly with the coroutine and put your data code in your composable (which isn't ideal) you can do something like this:
Copy code
@Composable
fun MyComposable() { 
  var theList by mutableStateOf(emptyList())

  LaunchedEffect(Unit) { 
    theList = getData().await()
  }

  theList.forEach { 
    // ...
  }
}
a
thanks it works !!
d
it's simple and it works, but normally I think you would turn it into a flow as part of a ViewModel or something to help modularize your code
Copy code
class MyViewModel { 
  val theListData: Flow<List<?>> = flow {
    emit(getData().await())
  }
}

@Composable
fun MyComposable(viewModel: MyViewModel) {
  val theList by viewModel.theListData.collectAsState(emptyList())
  theList.forEach {
    // ...
  }
}
a
Yes I know but it's a list that comes from a JSON that I fetch using
Ktor
and
kotlinx.serialization
, so I get the entire list at once so I don't need any flow, also the list is just less than 100 items, they have quite a lot of data but it's almost only literal values and other are not that big
a
I agree, for one emission, you don't need a flow at all