Home > Software design >  kotlinx.coroutines not found
kotlinx.coroutines not found

Time:08-02

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?

CodePudding user response:

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.

Gradle sync

Or by using the "Sync Now" button displayed on the screen when editing the gradle file.

  • Related