[英]How can I return value from execute of Executor - Kotlin
How can I return value from execute
of Executor
:如何从Executor
execute
返回值:
fun MyFunc(): Int {
private val executor: Executor =
Executors.newSingleThreadExecutor()
executor.execute { appRepository.tblCoursesIsEmptyAppRepo() }
}
I used from postValue
but it get me old value always.我从postValue
使用,但它总是让我得到旧值。
Use kotlin Coroutines it's very rich and concise than Executor and you can get a value of livedata by postValue() method.使用 kotlin Coroutines 它比 Executor 非常丰富和简洁,您可以通过 postValue() 方法获取 livedata 的值。
To use coroutine add gradle files:要使用协程添加 gradle 文件:
def coroutines_version = "1.3.3"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
and use below code:并使用以下代码:
val handler = CoroutineExceptionHandler { _, exception ->
exception.printStackTrace()
}
CoroutineScope(Dispatchers.IO).launch(handler) {
resultLiveData.postValue(appRepository.tblCoursesIsEmptyAppRepo())
}
I used from bellow source code and it good work:我从波纹管源代码中使用,效果很好:
val callable = Callable { appRepository.tblCoursesIsEmptyAppRepo() }
val future = Executors.newSingleThreadExecutor().submit(callable)
Log.i(TAG, future.get())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.