2017-11-17 5 views
1

다음 코드가 있습니다.비동기 작업 중이지만 기다리는 중 참조를 얻지 못했습니다

왜 이런 일이 일어나는 지 이해할 수 없습니다. 나는 이것을 다루는 SO에 대한 기존의 답을 찾지 못했다. 나는 tenny와 twy가 할당 된 곳에서 직접 기다리는 것을 시도했으나 그것도 작동하지 않습니다.

aysnc가 작동하기 때문에 종속성에 문제가 있다고 생각하지 않습니다. build.gradle 파일도 게시했습니다. 당신의 star_twostar_ten 기능 Int를 반환하기 때문에

import kotlinx.coroutines.experimental.async 

fun main(args: Array<String>) { 
    async{ 
     val tenny = star_ten(1) 
     val twy =star_two(10) 

     println() 
     println(twy.await()+tenny.await()) 
     println() 
    } 
} 

fun star_two(num:Int):Int{ 
    return num * 2 
} 
fun star_ten(num:Int):Int{ 
    return num * 10 
} 

내 build.gradle 그렇게 tennytwy 변수는 단지 Int입니다, 당신은 await()에 대한 해결되지 않은 참조를 얻고있다

group 'org.nul.cool' 
version '1.0-SNAPSHOT' 

buildscript { 
    ext.kotlin_version = '1.1.60' 

    repositories { 
     mavenCentral() 
    } 
    dependencies { 
     classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 
    } 
} 

apply plugin: 'java' 
apply plugin: 'kotlin' 

kotlin { 
    experimental { 
     coroutines 'enable' 
    } 
} 



sourceCompatibility = 1.8 

repositories { 
    mavenCentral() 
} 

dependencies { 
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version" 
    testCompile group: 'junit', name: 'junit', version: '4.12' 
    compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.19.2" 
} 

compileKotlin { 
    kotlinOptions.jvmTarget = "1.8" 
} 
compileTestKotlin { 
    kotlinOptions.jvmTarget = "1.8" 
} 

답변

2

입니다. await() 함수는 Deferred에 선언되어 있습니다. 간단히 말해서, 이러한 함수에서 비동기적인 작업을 수행하지 않으므로 기다릴 것이 없습니다.

이러한 함수가 비동기 적으로 동작하도록하는 한 가지 방법은이를 일시 중단 함수로 선언하고 비동기 블록에서 각 함수를 호출하는 것입니다. (안된) 이런 식으로 뭔가 ...

async{ 
    val tenny = async { star_ten(1) } //Should be Deferred<Int> 
    val twy = async { star_two(10)} //Should be Deferred<Int> 
    println(twy.await() + tenny.await()) 
} 

suspend fun star_two(num:Int): Int = num * 2 
suspend fun star_ten(num:Int): Int = num * 10 

Guide to kotlinx.coroutines by example 페이지, 특히 this section 많은 좋은 사례가있다.

관련 문제