在build.gradle中;
ext.KOTLIN_COROUTINE_VERSION = '1.3.0-M1'
在app / build.gradle中:
i
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)