https://kotlinlang.org logo
#compose
Title
# compose
m

martmists

10/14/2023, 3:17 PM
What's the best way to stream data to a LazyColumn? My current code does this:
Copy code
var allItems by remember { mutableStateOf(emptyList<Page>()) }

LaunchedEffect(filter) {
    println("Updating for $filter")
    val url = "<https://my.site/pages?per_page=100&search=${filter.encodeURLPath()}>"
    var checkForMore = true
    var page = 1
    val allPages = mutableListOf<Page>()

    while (checkForMore) {
        allItems = allPages

        val res = Globals.client.get("$url&page=$page")
        if (res.status != io.ktor.http.HttpStatusCode.OK) {
            checkForMore = false
            continue
        }
        val items = res.body<List<Page>>()

        if (items.isEmpty()) {
            checkForMore = false
        } else {
            allPages.addAll(items)
            page++
        }
    }

    allItems = allPages
    println("Done setting for $filter: $allPages")
}

println(allItems)

LazyColumn {
    items(allItems) { ... }
}
but for some reason when
filter
gets changed (from a
TextField
) it sometimes doesn't update properly, and although the "Done setting" println shows elements, nothing ends up being visible.
z

Zach Klippenstein (he/him) [MOD]

10/14/2023, 10:12 PM
Please keep code snippets more than a few lines to the thread to avoid cluttering the main channel, thanks
After
filter
changes, does “Updating for …” get printed?
a

ascii

10/15/2023, 12:18 PM
I'd sidestep this by asking why not put this into your data/network layer? It would be easier to test if this is isolated from Compose. Let JC be responsible only for UI & family. It doesn't need to, nor should, handle data retrieval except the
collectAsState*
bridge methods.
3
Coroutines are not uniquely tied to Compose. They can be used elsewhere too.
m

myanmarking

10/16/2023, 9:38 AM
probably your problem has do do with concurrency. there’s nothing preventing the allIItems from being messed up due to multiple ongoing requests
do the following. update ‘allItems’ just once at the end. That should work
this is not a good architecture imo. So many things can go wrong here. 1) what if there is a network error? 2) Two filters can race for results. 3) An outdated filter can finish first, etc. You should rethink this solution
even if the network call is cancellable, you are changing the list before the call. It will 100% bug eventually
m

martmists

10/19/2023, 7:30 PM
What would be a better approach?
3 Views