API design question - which would you use to pass ...
# coroutines
z
API design question - which would you use to pass around a read-only value that gets initialized once and cached? 1.
suspend () -> T
2.
Deferred<T>
Vote 1️⃣ for
suspend fun () -> T
or 2️⃣ for
Deferred<T>
1️⃣ 7
2️⃣ 4
I see
suspend () -> T
as a more abstract approach, but it requires more boilerplate + some extra anonymous classes
Deferred<T>
has a lot less boilerplate to implement, more clearly indicates that the value will be cached, but it exposes its underlying
Job
API, which a caller could accidentally cancel
o
if you're worried about the cancellation, just create a separate
CompletableDeferred
that's not part of the job.
z
CompletableDeferred
extends
Deferred
so it’s worse. This isn’t an API that you would want to allow callers to be able to complete. It’s read only
o
I don't mean return it -- I mean use it to prevent cancellation of the underlying job
you'd still return
Deferred<T>
, but internally you would hand-off the value to create a gap
z
oh, very interesting
d
Interface version of option 1 I think.
z
I’m not a fan of the interface approach as that is less flexible
z
interesting idea, but I would like to avoid introducing a custom type
l
Well, you can make the top level
val
private, and make a top level suspending function getting the value from it.