Issue
I'm writing React Native and implemented a custom UI component for Android. One of the props I send to the component is a large array of objects. The deserialization in Android (Kotlin) tooks some time (>200ms) and I'm trying to use async
to prevent blocking the UI.
@ReactProp(name = "items")
fun setItems(view: CustomListView, items: ReadableArray) {
async {
val itemsList = deserializItems(items)
view.setItems(itemsList)
}
}
but Android Studio says: Unresolved reference: async
I added these to my app build.gradle
:
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4"
and tried to import manually kotlinx.coroutines
but Android Studio doesn't find it as well.
How can I get async
functionality in Android?
Solution
You need a coroutine scope to be able to call async
.
I am not familiar with react development, but how i would use it something like this from inside a viewModel.
val asyncFunction = viewModelScope.async {
//do your background work here
}
and then you need to await()
it later.
viewModelScope.launch {
asyncFunction.await()
}
For import i have this in the gradle files
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'
and these are the imports
import kotlinx.coroutines.*
Also, it might sound silly, but make sure to sync gradle after adding the dependencies.
Or by using the "Sync Now" button displayed on the screen when editing the gradle file.
Answered By - Ionut
Answer Checked By - Timothy Miller (JavaFixing Admin)