Sumit Shukla
Sumit Shukla

Reputation: 4514

Get coroutine scope reference inside anonymous inner class

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

Answers (1)

Glenn Sandoval
Glenn Sandoval

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

Related Questions