Kotlin协程,是否有更好的方法返回此值? [英] Kotlin coroutines, is there a better way to return this value?
问题描述
与协程作斗争,但是在通过回调将其传递到另一个网络协程之前,是否有更好的方法使用/获取长时间运行的调用的值?我见过其他人,但比起我似乎无法在最新的droid coroutine版本中使用该值,就像我似乎无法使这项工作有效
Struggling with coroutines, but is there a better way to use/get the value for a long running call out here before passing it onto another network coroutine with the callback? I've seen others but than i can't seem to use the value with the latest droid coroutine release, like I can't seem make this work Kotlin Coroutines with returning value
private suspend fun launchGeneratePayload(): String? {
return withContext (Dispatchers.Default) {
try {
val payloadString = slowStringGeneration()//Slow
return@withContext payloadString
} catch (e: java.lang.Exception) {
return@withContext null
}
}
}
最终使用该值的地方
public someFunction(callback: CallBack) {
val params: JSONObject = JSONObject()
params.put("param1", "param1Value")
runBlocking{ //probably should be launch or similar
val payload = launchGeneratePayload()
params.put("param2", payload)
//call network function with params & callback
//networkCall (
}
}
感谢您的帮助
edit:我认为实际上正在寻找的东西与
edit: I think was actually looking for was just a bit different with
suspend fun launchGeneratePayload(): String? =
withContext(Dispatchers.Default) {
try {
slowStringGeneration() //slow
} catch (e: java.lang.Exception) {
null
}
}
}
稍后在我仍然不愿意回答时,将添加为答案.
Will add as an answer later incase i'm still off on this/else.
推荐答案
您可以使用 launch
协程生成器来启动协程:
You can use launch
coroutine builder to start the coroutine:
private var job: Job = Job()
private var scope = CoroutineScope(Dispatchers.Main + job)
fun someFunction(callback: CallBack) {
val params: JSONObject = JSONObject()
params.put("param1", "param1Value")
scope.launch { // launch the coroutine
val payload = generatePayload() // generate String without blocking the main thread
params.put("param2", payload)
//call network function with params & callback
//networkCall (params, callback)
}
}
suspend fun generatePayload(): String? = withContext(Dispatchers.Default) {
try {
slowStringGeneration() //slow
} catch (e: java.lang.Exception) {
null
}
}
注意:您还可以将 networkCall()
设置为挂起,这样就无需使用回调
.
Note: you can also make networkCall()
as suspend, then you won't need to use callback
.
要在Android中使用 Dispatchers.Main
,请向应用程序的build.gradle文件添加依赖项
To use Dispatchers.Main
in Android add dependency to the app's build.gradle file
实施'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.1'
这篇关于Kotlin协程,是否有更好的方法返回此值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!