Hi, what is the convention when having a suspend a...
# announcements
a
Hi, what is the convention when having a suspend and non-suspend version of the same method, which one contains the actual implementation? For example, when having a
get()
method (non-suspend) and a
getAsync()
method (suspendable), which one should own the logic/implementation? Option 1 (suspendable owns the logic/implementation):
Copy code
fun get(): String {
  return runBlocking {
    getAsync()
  }
}

suspend fun getAsync(): String {
	  // actual getter logic
}
Option 2 (non-suspendable owns the logic/implementation):
Copy code
fun get(): String {
  // actual getter logic
}

suspend fun getAsync(): String {
  	withContext(dispatchers.default()) {
		return get()
	}
}
e
When the actual logic is non-blocking, the call it by the the simple name and name the one that wraps it with runBlocking using
Blocking
suffix. For example, see `send`/`sendBlocking` pair.
Also, there is a special #C1CFAFJSK channel
It the second case, it makes sense to expose only suspending implementation. The actual logic should be better private with some kind of
Impl
suffix in its name.
a
Use
Async
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
.
Copy code
suspend fun get(): String {
    // main logic
}
Copy code
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.
a
The answers in this thread. wooooow, so beautifuk
a
Thanks a lot for the explanations @romanbehul @Animesh Sahu, so I guess the better option suggested would look like this:
Copy code
fun 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.