The getPercentage function creates a coroutine in the background via the launch function, and then continues without waiting. Your "outside" code is therefore running before the "inner" coroutine completes.
The first option is to use the async function instead to return a Deferred value from the coroutine:
fun getPercentage(id:String): Deferred<String> {
return scope.async {
percentage=repo.getPercentage(id)?.get(0)?.percent.toString()
Log.e("$$$ value >>","$$$ value >>"+percentage)
}
}
Note of course that its more likely you want to make getPercentage a suspend function, and then call await directly:
suspend fun getPercentage(id:String): String {
val percentageDeferred = scope.async {
percentage=repo.getPercentage(id)?.get(0)?.percent.toString()
Log.e("$$$ value >>","$$$ value >>"+percentage)
}
val percentage = percentageDeferred.await()
Log.e("$$$ value outside >>","$$$ value >>"+percentage)
return percentage
}
It's also likely you want to do something else before the await otherwise you're probably just better off making repo.getPercentage a suspend function as well, and calling it directly:
suspend fun getPercentage(id:String): String {
// if repo.getPercentage is a suspend function, this call suspends
// like the await in the previous example
val percentage = repo.getPercentage(id)?.get(0)?.percent.toString()
Log.e("$$$ value outside >>","$$$ value >>"+percentage)
return percentage
}
See Concurrent using async in the Kotlin docs.