Alberto
11/17/2020, 4:29 AMget() method (non-suspend) and a getAsync() method (suspendable), which one should own the logic/implementation?
Option 1 (suspendable owns the logic/implementation):
fun get(): String {
return runBlocking {
getAsync()
}
}
suspend fun getAsync(): String {
// actual getter logic
}
Option 2 (non-suspendable owns the logic/implementation):
fun get(): String {
// actual getter logic
}
suspend fun getAsync(): String {
withContext(dispatchers.default()) {
return get()
}
}elizarov
11/17/2020, 6:23 AMBlocking suffix. For example, see `send`/`sendBlocking` pair.elizarov
11/17/2020, 6:23 AMelizarov
11/17/2020, 6:25 AMImpl suffix in its name.Animesh Sahu
11/17/2020, 9:58 AMAsync suffix when the function is not marked with suspend but returns a Deferred<T> from CoroutineScope.async .
Use Blocking suffix when it wrap around a blocking code and is non-suspendable.
Use no suffix/prefix when function is suspend .Animesh Sahu
11/17/2020, 10:01 AMsuspend fun get(): String {
// main logic
}
fun getAsync(scope: CoroutineScope = GlobalScope): Deferred<String> =
scope.async { get() }
Seems a good fit.
The caller can do getAsync().invokeOnCompletion { .. } if he is not under a coroutine, or .await() to suspend and get the result.andylamax
11/17/2020, 12:38 PMAlberto
11/17/2020, 2:54 PMfun getBlocking(): String = runBlocking {
get()
}
suspend fun get(): String {
// actual getter logic
}
regarding which ones to expose, I wanted to expose both and let clients of this API choose which one to use.