Hi everyone, Question: How to idiomatically add su...
# library-development
l
Hi everyone, Question: How to idiomatically add suspend variants of existing fire-and-forget API methods? We have an Android SDK with a Player interface that has fire-and-forget methods. Completion/failure is signaled via events:
Copy code
interface Player : EventEmitter<PlayerEvent> {                                                                                                                                                                                                                                                                                                                                                                                                         
   fun play()                // completion: PlayerEvent.Playing / PlayerEvent.Error                                                                                                                                                                                        
....                                                                                                                                                                                                   
}
We want to add suspending variants that await the corresponding completion event. The existing non-suspend API must stay as-is since we don't want to break backwards compatibility. What's the idiomatic Kotlin approach here? Is there an established pattern we're missing?
d
Hi! I'd expect https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/suspend-cancellable-coroutine.html to be used for this. The code snippet at the top of the KDoc looks fairly similar to the interaction you're describing.
l
Thanks @Dmitry Khalanskiy [JB], this makes a lot of sense. From an API perspective, how would an idiomatic naming look like here? E.g.
suspend awaitPlay()
? Same name overloads don't seem to work (i.e.
suspend play()
).
At least not on the same interface or as extension functions.
d
I don't know of any popular `suspend`/non-
suspend
method pairs, so I'm not sure there is an established naming convention for that scenario. An approach I've seen in the wild is to have two separate interfaces:
Player
and
AsyncPlayer
, with
fun Player.asAsyncPlayer(): AsyncPlayer
. Then,
AsyncPlayer
could also have
suspend fun play()
.
l
Thanks @Dmitry Khalanskiy [JB], for your insights. This sounds like a sound approach. 🙇
🎉 1