[英]How to get FragmentActivity reference inside an anonymous inner class of bindView method?
[英]Get coroutine scope reference inside anonymous inner class
lifecycleScope
范圍在片段內進行簡單的 api 調用,以獲取一些數據並將其存儲在Room database
中。CoroutineScope
的引用來調用暫停方法,因為Anonymous Inner Class 。 如何獲得當前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。
您可以使用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)
}
})
}
你可以這樣稱呼它:
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.