Pemba Tamang
Pemba Tamang

Reputation: 1052

How to return a value from a coroutine from a method that is non suspending?

What I've tried so far

   fun getCPByID(ids: List<Int>): List<CheckingPointVo>  {
        var list : List<CheckingPointVo> = emptyList()
       coroutineScope.launch {
              
           list =  someMethod()
       }
        return list
    }

here I tried to use async and await but that cannot be run from a non suspend function. Is there a way to do this ?

Upvotes: 2

Views: 1241

Answers (1)

R&#243;bert Nagy
R&#243;bert Nagy

Reputation: 7690

Not really with the current structure, you're basically trying to combine synchronous code with async.

You have 3 possible options though to make it async:

  1. Use a callback:
 fun getCPByID(ids: List<Int>, listCallback: (List<CheckingPointVo>) -> Unit) {
       coroutineScope.launch {      
           listCallback(someMethod())
       }
    }

Note: If you're using it from Java, this should work with either Java lambdas or Function. But you may create an interface for this, like :

Interface ListCallback {
    fun onListReceived(list: List<CheckingPointVo>)
}

fun getCPByID(ids: List<Int>, listCallback: ListCallback) {
    .... // Same implementation
 }

// Call it from Java
getCPByID(ids, new ListCallback() {
    void onListReceived(List<CheckingPointVo> list) {
         ...
    }
});
  1. Use either an observable pattern, use a Flow or LiveData. A possible example:
 fun getCPByID(ids: List<Int>) = coroutineScope.launch {
           flow {
               emit(someMethod())
           }
       }
    }
  1. Make your function a suspend function and use coroutineScope.launch from the caller

Upvotes: 2

Related Questions