在 Kotlin 中未解决的 async 引用

21

我正在尝试在Kotlin中异步执行网络操作。 我读到可以使用async函数进行异步处理。但是我遇到了以下错误,有人能猜测可能出了什么问题吗?

未解决的引用: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)
    }
}

顶级 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
}

模块级别的 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'
}

你不小心在这里张贴了你的APP_ID(?)。除非此API还需要一个API密钥,否则你应该立即禁用它并获取一个新的APP_ID。 - Christian Brüggemann
@ChristianBrüggemann 啊,已经移除了 :) - N Sharma
2
@Williams,这仍然是问题更改日志中的历史记录,如果您不希望有任何非法使用您的APP_ID,请更改它。 - Jayson Minard
4个回答

22

async可以在kotlinx.couroutines中使用。

请确保您已在gradle文件中添加了依赖关系:

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

同样确保异步调用在协程作用域中,例如 GlobalScope

 val deferredResult = GlobalScope.async {

            }

4

我看到在Kotlin库本身并没有提供async函数,但是在anko库中可以找到。您可以前往https://github.com/Kotlin/anko查看。

为了解决这个问题,我在build.gradle中添加了以下依赖:compile "org.jetbrains.anko:anko-commons:0.10.1",因为这个函数在Kotlin本身中不可用。

我发现async现在已经过时了,库建议使用doAsync代替。

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

2

0
如果您正在使用Deferred,请确保导入了kotlinx.coroutines.Deferred,还有可能会导入firebase Deferred。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接