What's the recommended way to handle, on a single ...
# compose
s
What's the recommended way to handle, on a single
@Composable fun
, load initial at ID, HTTP GET, load internal `Composable`s based on that data? My current approach:
Copy code
var lastErrorStr by remember { mutableStateOf("") }
val thingName by remember { mutableStateOf("") }
val thingImgUrl by remember { mutableStateOf("") }
val myId by remember { mutableStateOf(myIdFromInputOfThisFunc) }
val scope = rememberCoroutineScope()
TextField(value = myId, label = { Text("enter ID") })
LaunchedEffect(myId) {
    try {
        val thing = scope.async {
              myApi.getById(barcode)
        }.await().thing
        thingName = thing.name
        thingImgUrl = thing.imgUrl
    } catch (e: SocketTimeoutException) {
                lastErrorStr = "[SocketTimeoutException] ${e.message}"
    } /* other error handling omitted for brevity */
}
AnimatedVisibility(thingName.isNotEmpty()
                && lastErrorStr.isEmpty()) {
    Text(thingName)
    AnimatedVisibility(thingImgUrl.isNotEmpty()) {
        SubcomposeAsyncImage(model = thingImgUrl)
    }
}
AnimatedVisibility(lastErrorStr.isNotEmpty()) {
    Text(lastErrorStr, color = Color.Red)
}
m
From an architecture standpoint, it feels like a composable should not be doing network I/O directly. Typical architectures have network I/O be handled elsewhere, such as in a repository.
s
Yeah it certainly feels awkward the way I'm writing; which is why I'm asking here for alternative architectural recommendations. FYI: I target desktop, web, iOS, Android
d
I would recommend an MVVM architecture with StateFlows. The view model is the layer between the view and the data source, and it performs any business logic on the data required before sending it to the view. The view in this case is your composable Phillip Lackner has some videos on it for compose multiplatform and there are plenty of resources out there for learning the MVVM pattern.
☝️ 1
s
Ok checking him out, yeah I recently heard about MVI also and he's got a video comparing the two so will watch. Thanks