[英]Get coroutine scope reference inside anonymous inner class
lifecycleScope
to make a simple api call inside a fragment to get some data and store it in Room database
.lifecycleScope
范围在片段内进行简单的 api 调用,以获取一些数据并将其存储在Room database
中。CoroutineScope
to call a suspension method because of Anonymous Inner Class .CoroutineScope
的引用来调用暂停方法,因为Anonymous Inner Class 。 How can I get reference of the current CoroutineScope
?CoroutineScope
的参考? Demo:演示:
lifecycleScope.launch {
SomeClass(context).getDataFromApi( object : CallBackResult<Any> {
override fun onSuccess(result: Any) {
saveToLocal() // I have to call a suspension function from here
}
})
}
suspend fun saveToLocal() {
//save some data
}
Note: I am not following MVVM Pattern but MVC.注意:我不是遵循 MVVM 模式,而是遵循 MVC。
You could make use of suspendCancellableCoroutine
to turn your blocking API call into a suspending function:您可以使用
suspendCancellableCoroutine
将您的阻塞 API 调用转换为暂停 function:
suspend fun getDataFromApi(context: Context): Any = suspendCancellableCoroutine { continuation ->
SomeClass(context).getDataFromApi( object : CallBackResult<Any> {
override fun onSuccess(result: Any) {
continuation.resume(result)
}
})
}
And you can call it like this:你可以这样称呼它:
lifecycleScope.launch(Dispatchers.IO) {
val result = getDataFromApi(context) //Here you get your API call result to use it wherever you need
saveToLocal()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.