Hi, I'm trying to pass a variable out of my Launch...
# compose
n
Hi, I'm trying to pass a variable out of my LaunchedEffect so I can use it. I'm not sure how to accomplish that. Any ideas?
Copy code
@Composable
fun CallApi() {
    LaunchedEffect(key1 = {}, block = {
        val retrofitData = retrofitBuilder.getBooks("flower")
    })
    LazyColumn(content = {
        item {
            for (item in retrofitData.items) {
                Text(text = item.volumeInfo.title)
            }
        }
    })
}
Copy code
The problem is getting retrofitData
z
Use a
MutableState
, something like this:
Copy code
var retrofitData by remember { mutableStateOf(emptyList()) }
LaunchedEffect(retrofit) {
  retrofitData = retrofit.getBooks("flower")
}
LazyColumn(…
Make sure to pass any dependencies used in your lambda as keys, in this case the retrofit object. This pattern is common enough that there’s a helper for it:
Copy code
val retrofitData by produceState(initialValue = emptyList(), key1 = retrofit) {
  retrofit.getBooks("flower")
}
😊 1
n
Brilliant, thank you so much!
a
you'll want a
value =
in there but otherwise yes 🙂
🙏 1
z
Oops yea, I always forget about that
c
Most of this is going over my head (mostly due to me being unfamiliar/unsure of my own knowledge on LaunchedEffect) Nat, just out of curiosity, what are you accomplishing with your code snippet here? I'm intrigued 😄
n
I'm retrieving book details from the Google Books api, ie a list of book titles that match the search term "flower", and displaying it in a LazyColumn. 😊
c
Why is this being done in a LaunchedEffect though? Wouldn't your ViewModel (or similar) be in charge of fetching?
n
The interface that does the fetching is a suspend function...
Lol, I'm not an expert at all. I'm trying to work it out myself. 😉