https://kotlinlang.org logo
#coroutines
Title
# coroutines
j

joelpedraza

03/21/2019, 2:09 PM
fun <A, B> Deferred<Pair<A, B>>.split(): Pair<Deferred<A>, Deferred<B>>
Is this possible?
g

gildor

03/21/2019, 2:09 PM
Depends on how you want to use it
j

joelpedraza

03/21/2019, 2:10 PM
I dont know yet, I’m just getting started with coroutines
g

gildor

03/21/2019, 2:10 PM
What is your use case?
Because of course you can invert it like this, but it would be just wrapping result to 2 more deferred
j

joelpedraza

03/21/2019, 2:11 PM
Producer returns
A
and
B
, Consumer may need
A
,
B
,
A && B
, or neither and won’t know which until runtime
So I’d just like to be able to split and await both if the predicate for each is true
g

gildor

03/21/2019, 2:13 PM
Copy code
async { val (a, _) = await(); a } to async { val (_, b) = await(); b }
something like this
s

streetsofboston

03/21/2019, 2:13 PM
If you await either or both, you no longer need to wrap them in a `Deferred`…
j

joelpedraza

03/21/2019, 2:13 PM
💡
g

gildor

03/21/2019, 2:13 PM
It’s just not really common to have such operators for Deferred
It’s recommended to use suspend functions everywhere where it’s possible, so it’s quite interesting case if you really need to work with deferred directly
I agree with Anton, at least this is true in most of cases, but maybe you have more special use case for this
j

joelpedraza

03/21/2019, 2:20 PM
I’m not yet sure, I’m really very new to coroutines. But there is the case where the consumer does not need the data from the producer at all. Use case is speculative prefetching
We’ll probably need one of
A
or
B
but dont know at the time the consumer starts aggregating data
s

streetsofboston

03/21/2019, 2:26 PM
What about your own sealed type
Result<out A, out B>
with sub-types
Left<out A> : Result<A, Nothing>
,
Right<out B> : Result<Nothing, B>
,
Both<out A, out B> : Result<A,B>
and
None : Result<Nothing, Nothing>
?
The values for A and/or B are obtained by awaiting for one/both of them
r

raulraja

03/21/2019, 5:25 PM
That is IOR. It can represent an inclusive OR where you may have either value or both
You can use that or rip it off from the sources with only the API you need
It's a basic sealed class ADT like Either or what is called here Result
With an extra case for Both a b
g

gildor

03/22/2019, 1:22 AM
But there is the case where the consumer does not need the data from the producer at all
I would start from another question: what is your use case to have Deferred?
2 Views