Reputation: 4514
lifecycleScope
to make a simple api call inside a fragment to get some data and store it in Room database
.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.
Upvotes: 2
Views: 989
Reputation: 3745
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()
}
Upvotes: 4