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
Derek Ellis
08/06/2022, 12:42 AM
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
Ayfri
08/06/2022, 12:43 AM
And what is the design pattern for data coming from a coroutine ? :>
d
Derek Ellis
08/06/2022, 12:45 AM
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
Ayfri
08/06/2022, 12:47 AM
thanks it works !!
d
Derek Ellis
08/06/2022, 12:48 AM
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
Ayfri
08/06/2022, 12:50 AM
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
andylamax
08/07/2022, 10:50 PM
I agree, for one emission, you don't need a flow at all