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

Nat Strangerweather

12/13/2021, 10:29 PM
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

Zach Klippenstein (he/him) [MOD]

12/13/2021, 10:51 PM
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

Nat Strangerweather

12/13/2021, 10:57 PM
Brilliant, thank you so much!
a

Adam Powell

12/14/2021, 2:39 AM
you'll want a
value =
in there but otherwise yes 🙂
🙏 1
z

Zach Klippenstein (he/him) [MOD]

12/14/2021, 2:54 AM
Oops yea, I always forget about that
c

Colton Idle

12/14/2021, 5:32 PM
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

Nat Strangerweather

12/14/2021, 8:30 PM
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

Colton Idle

12/14/2021, 8:37 PM
Why is this being done in a LaunchedEffect though? Wouldn't your ViewModel (or similar) be in charge of fetching?
n

Nat Strangerweather

12/14/2021, 8:42 PM
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. 😉