https://kotlinlang.org logo
Title
e

efemoney

02/09/2021, 11:01 AM
Do I need to explictly
close
a channel if I only want to
receive
a single value from it? Something like this inside some suspend function
val whatIWant = myChannel.receive()
myChannel.close()
return whatIWant

// VS

return mychannel.receive()
v

Vivek Sharma

02/09/2021, 11:09 AM
I think no, but for if you want to be secure that, no more values should be send on the channel then yes
m

marstran

02/09/2021, 11:14 AM
Are you sure using a
Channel
is the correct approach if you only want to receive a single value?
e

efemoney

02/09/2021, 11:17 AM
Yeah @marstran, channel elements can be offered asynchronously via some callback
v

Vivek Sharma

02/09/2021, 11:17 AM
if you want to receive a single value, we can use channel and then receive them as flow @marstran
e

efemoney

02/09/2021, 11:19 AM
I have doubts if its needed to convert to flow. Whats the real difference between
myChannel.receiveAsFlow().first()
// AND
myChannel.receive()
v

Vivek Sharma

02/09/2021, 11:24 AM
receiveAsFlow convert channel to hotflow, whenever something is send to channel, stateflow will be collecting values
e

efemoney

02/09/2021, 11:25 AM
Yeah I know that. But specificallhy for the example above, what is the effect other than the unnecessary indirection via flow?
v

Vivek Sharma

02/09/2021, 11:25 AM
you should check by trying I think, how both works
m

marstran

02/09/2021, 11:51 AM
If all you need is to retrieve a value from a callback, you could just use
suspendCancellableCoroutine
to convert the callback-function to a normal suspend function.
☝️ 1
👍 1
If the callback can be called multiple times, you can use
callbackFlow
instead.
e

efemoney

02/09/2021, 11:58 AM
Yeah you are absolutely correct @marstran. I might not need a channel after all.
👍 1