简体   繁体   English

在匿名内部 class 中获取协程 scope 引用

[英]Get coroutine scope reference inside anonymous inner class

  • I am using lifecycleScope to make a simple api call inside a fragment to get some data and store it in Room database .我正在使用lifecycleScope范围在片段内进行简单的 api 调用,以获取一些数据并将其存储在Room database中。
  • As soon as I get a response inside Anonymous Inner Class I cannot get a reference of CoroutineScope to call a suspension method because of Anonymous Inner Class .一旦我在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM