I am calling an API in an asynchronous function, and would like to store the response from the callback.
Specifically, I am using the API category of AWS Amplify in an Android app, and would like to assign the return value to a LiveData variable in a ViewModel.
fun getMuscleGroup(id: String): ExampleData {
var exampleData = ExampleData.builder().name("").build()
Amplify.API.query(
ModelQuery.get(ExampleData::class.java, id),
{ response ->
Log.d("AmplifyApi", response.data.name)
exampleData = response.data
},
{ error -> Log.e("AmplifyApi", "Query failure", error) }
)
return exampleData
}
I can receive the response and it gets logged correctly, but the response is not assigned to the exampleData variable, since the function returns early.
In Android Studio, the variable exampleData is highlighted with the text:
Wrapped into a reference object to be modified when captured in a closure
As I am not that familiar with the multithreading APIs in kotlin, I am not sure, how to block the function until the remote API returns its asynchronous response.