我正在尝试将协程添加到现有应用程序中,但我终生无法正常工作。首先,我是一个.net开发人员,被要求重写android应用程序,因此我试图避免留在回调炼狱中。
我已经完成以下工作: 将这些实现添加到应用程序build.gradle
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.50"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3'
在项目build.gradle中添加以下内容 注意-还确保jcenter等...包括werre
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.10'
gradle同步过程按预期方式进行...
当我要在应用程序中编写一些代码时,我永远无法使示例在线正常工作。 对于初学者,有什么乐趣?我收到一条消息,指示未识别符号“有趣”。我为此缺少一些参考。另外,“ suspend”和“ val”也无法识别,因此我想我在那里也缺少了一些东西。
我确实在这里找到了一个似乎确实有效的示例...
BuildersKt.launch(
GlobalScope.INSTANCE,
Dispatchers.getMain(), // Run on the Main UI Thread
CoroutineStart.DEFAULT,
new Function2<CoroutineScope, Continuation<? super Unit>, Object>() {
@Override
public Unit invoke(CoroutineScope coroutineScope, Continuation<? super Unit> continuation) {
//do what you want
return Unit.INSTANCE;
}
}
);
这里有很多我不理解的地方,说实话,语法似乎也不是很干净。
我希望能够编写如下内容:
suspend fun computeValue(): String = coroutineScope {
val one = async { computeOne() }
val two = async { computeTwo() }
combineResults(one, two)
}
老实说,我很难找到有关如何正确执行操作的文档。 谁能提供一个例子吗? 我正在寻找像下面这样的完整示例...
implementation 'ord.every.single.needed.dependency.listed'
public class StringManager {
public String getString1() {
return "String1";
}
public String getString2() {
return "String2";
}
}
// Are any decorators necessary
// Do I have to implement or extend anything
MainActvity {
public void Test() { // does this have to be a fun? if so how do I actually get the compiler to understand what fun is?
String val1 = async { stringManager.getString1(); }
String val2 = async { stringManager.getString2(); }
}
}
再次请记住,我不是要成为Java和android开发方面的专家,而只是寻找有关如何使其运行的示例。另外,如果您有任何在线参考文档或教程可以提供更多信息,这将对我很有帮助。