如何 return 来自非挂起方法的协程的值?
How to return a value from a coroutine from a method that is non suspending?
到目前为止我尝试了什么
fun getCPByID(ids: List<Int>): List<CheckingPointVo> {
var list : List<CheckingPointVo> = emptyList()
coroutineScope.launch {
list = someMethod()
}
return list
}
我在这里尝试使用 async 和 await,但这不能 运行 来自非挂起函数。有办法吗?
目前的结构并不是这样,您基本上是在尝试将同步代码与异步代码结合起来。
你有 3 个可能的选项来使其异步:
- 使用回调:
fun getCPByID(ids: List<Int>, listCallback: (List<CheckingPointVo>) -> Unit) {
coroutineScope.launch {
listCallback(someMethod())
}
}
注意:如果您在 Java 中使用它,它应该与 Java lambda 或 Function
一起使用。但是您可以为此创建一个接口,例如:
Interface ListCallback {
fun onListReceived(list: List<CheckingPointVo>)
}
fun getCPByID(ids: List<Int>, listCallback: ListCallback) {
.... // Same implementation
}
// Call it from Java
getCPByID(ids, new ListCallback() {
void onListReceived(List<CheckingPointVo> list) {
...
}
});
- 使用可观察的模式,使用
Flow
或 LiveData
。一个可能的例子:
fun getCPByID(ids: List<Int>) = coroutineScope.launch {
flow {
emit(someMethod())
}
}
}
- 将您的函数设为
suspend
函数并使用来自调用者的 coroutineScope.launch
到目前为止我尝试了什么
fun getCPByID(ids: List<Int>): List<CheckingPointVo> {
var list : List<CheckingPointVo> = emptyList()
coroutineScope.launch {
list = someMethod()
}
return list
}
我在这里尝试使用 async 和 await,但这不能 运行 来自非挂起函数。有办法吗?
目前的结构并不是这样,您基本上是在尝试将同步代码与异步代码结合起来。
你有 3 个可能的选项来使其异步:
- 使用回调:
fun getCPByID(ids: List<Int>, listCallback: (List<CheckingPointVo>) -> Unit) {
coroutineScope.launch {
listCallback(someMethod())
}
}
注意:如果您在 Java 中使用它,它应该与 Java lambda 或 Function
一起使用。但是您可以为此创建一个接口,例如:
Interface ListCallback {
fun onListReceived(list: List<CheckingPointVo>)
}
fun getCPByID(ids: List<Int>, listCallback: ListCallback) {
.... // Same implementation
}
// Call it from Java
getCPByID(ids, new ListCallback() {
void onListReceived(List<CheckingPointVo> list) {
...
}
});
- 使用可观察的模式,使用
Flow
或LiveData
。一个可能的例子:
fun getCPByID(ids: List<Int>) = coroutineScope.launch {
flow {
emit(someMethod())
}
}
}
- 将您的函数设为
suspend
函数并使用来自调用者的coroutineScope.launch