1

在 build.gradle;

ext.KOTLIN_COROUTINE_VERSION = '1.3.0-M1'

在 app/build.gradle 中:

一世

mplementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
    implementation 'com.yuyh.json:jsonviewer:1.0.6'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$KOTLIN_VERSION"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$KOTLIN_COROUTINE_VERSION"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$KOTLIN_COROUTINE_VERSION"

在我的 Android 应用程序中,我在TestActivity.kt中有 Kotlin 代码:

val traderMonitorRestClient = RestClientFactory.createRestClient(TraderMonitorRestClient::class.java)

        GlobalScope.launch(Dispatchers.Main) {
            val traidersListDeffered = traderMonitorRestClient.getTraidersList2()
            try {
                val response: Response<List<Trader>> = traidersListDeffered.await()
                // call after return response (e.g. after 10 seconds)
                Debug.d(TAG, "onCreate_after_wait")
                if (response.isSuccessful) { // Returns true if {@link #code()} is in the range [200..300). */
                    val responseAsString = response.body().toString()
                } else {
                    Debug.d(TAG, "onCreate_response_error = $response.code()")
                }
            } catch (e: HttpException) {
                Debug.e(TAG, e.message, e)
            } catch (e: Throwable) {
                Debug.e(TAG, e.message, e)
            }
        }
    }

好的。它工作正常。

现在我想在 java 文件中使用相同的代码 - TradersViewModel.java

我试试这个:

    import kotlinx.coroutines.Dispatchers;
    import kotlinx.coroutines.GlobalScope;

public class TradersViewModel extends ViewModel {

    private void loadData() {
            TraderMonitorRestClient traderMonitorRestClient = RestClientFactory.createRestClient(TraderMonitorRestClient.class);
            GlobalScope.launch(Dispatchers.getMain()) {

            }
        }

}

但我有编译错误:

Cannot resolve method 'launch(kotlinx.coroutines.MainCoroutineDispatcher)
4

0 回答 0