lifecycleScope
在片段内进行简单的api调用,以获取一些数据并将其存储在Room database
中。CoroutineScope
的引用来调用暂停方法。如何获得当前CoroutineScope
的引用?演示:
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
}
注意:我不是遵循MVVM模式,而是遵循MVC。
答案 0 :(得分:4)
您可以利用suspendCancellableCoroutine
将阻止的API调用转换为挂起函数:
suspend fun getDataFromApi(context: Context): Any = suspendCancellableCoroutine { continuation ->
SomeClass(context).getDataFromApi( object : CallBackResult<Any> {
override fun onSuccess(result: Any) {
continuation.resume(result)
}
})
}
您可以这样称呼它:
lifecycleScope.launch(Dispatchers.IO) {
val result = getDataFromApi(context) //Here you get your API call result to use it wherever you need
saveToLocal()
}