简体   繁体   中英

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 .
  • 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 . How can I get reference of the current 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.

You could make use of suspendCancellableCoroutine to turn your blocking API call into a suspending 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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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