Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unresolved reference async in Kotlin

Tags:

android

kotlin

I am trying to perform network operation async in Kotlin. I read it you can do async using async function. I am getting below error, can anyone guess what could be the issue ?

Unresolved reference: async

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    async() {
        val forecastWeather = ForecastRequest("302015").execute()
        Log.d("Test", forecastWeather.toString())
    }
}

ForecastRequest.kt

class ForecastRequest(val zipcode: String) {
    companion object {
        private val APP_ID = "XYZ"
        private val URL = "http://api.openweathermap.org/data/2.5/" +
                    "forecast/daily?mode=json&units=metric&cnt=7"
        private val COMPLETE_URL = "$URL&APPID=$APP_ID&q="
    }

    fun execute(): ForecastResponse {
        val forecastJsonStr = java.net.URL(COMPLETE_URL + zipcode).readText()
        return Gson().fromJson(forecastJsonStr, ForecastResponse::class.java)
    }
}

Top level build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Module level build.gradle

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.williams.thirddemo"
        minSdkVersion 23
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.code.gson:gson:2.8.1'
}
like image 807
N Sharma Avatar asked Jun 04 '17 12:06

N Sharma


People also ask

How do I fix kotlin unresolved reference?

gradle file, the import kotlinx line above will trigger the unresolved reference issue. Please make sure that you add the id 'kotlin-android-extensions' line on the build. gradle file that's inside your app module. Once you sync the Gradle build, the error should disappear.

What is async and await in Android?

Async is basically performing a task and return a result. launch{} does not return anything. async{ }, which has an await() function returns the result of the coroutine. launch{} cannot be used when you need the parallel execution of network calls. Use async only when you need the parallel execution network calls.


3 Answers

async is available inside kotlinx.couroutines

Make sure that you added the dependency in your gradle file:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1'

Also make sure that the async is called on a coroutine scrope such as GlobalScope.

 val deferredResult = GlobalScope.async {

            }
like image 57
Mahmoud Avatar answered Oct 19 '22 21:10

Mahmoud


I see async function is available in anko library not Kotlin library itself. https://github.com/Kotlin/anko

I resolved by adding this dependency in build.gradle compile "org.jetbrains.anko:anko-commons:0.10.1" as this is not available in Kotlin itself.

I see that async is deprecated now, library suggests to use doAsync instead.

doAsync {
    val forecastWeather = ForecastRequest("302015").execute()
    uiThread {
        Log.d("Test", forecastWeather.toString())
    }
}
like image 28
N Sharma Avatar answered Oct 19 '22 19:10

N Sharma


Different Kotlin libraries can have different implementations of async that do different things.

If you wanted the general async-await function from the core library, make sure you have a dependency to kotlinx.coroutines

like image 2
voddan Avatar answered Oct 19 '22 19:10

voddan