How do I convert this into less janky and actually...
# coroutines
k
How do I convert this into less janky and actually working code
😕 1
This is the log btw
m
So, what are you trying to do?
k
I'm reading raw bytes from a ByteReadChannel and if i got a cipher i encrypt and then send those bytes int a different ByteChannel
the problem is that ByteChannel#Read requires a normal lambda and not a suspending one which is causing all the problems
I fixed it by moving the Job initialiser outside of the while loop 🤦‍♂️
But still the code looks jank
I'm extracting it to a extensionfunction for the time being
m
So the read-lambda is a callback right?
k
yeah
m
Ok, then you should convert it to a coroutine with the
suspendCoroutine
function. Check out this article: https://medium.com/@elizarov/callbacks-and-kotlin-flows-2b53aa2525cf
p
Which functions are suspending in launch? Maybe you could use a channelFlow instead of the nullable Job to pass the data
k
What do you mean?
I'm writing to a second byteChannel
those writes are suspending
in the future it might be converted into a channel of a certain type but that requires some refactoring and wrappers and i first want my code working
I'm guessing my question is: Is there a variant for read that allows supension?
m
So something like
Copy code
suspend fun ByteChannel.read(): ByteBuffer = suspendCoroutine { continuation -> 
  read { continuation.resume(it) }
}
k
doesn't seem to work
message has been deleted
this also feels janky
m
Weird error you get in the first one. You said
read
isn't suspending, right?
Could you try renaming your function to
readSuspending
?
k
read is suspending
m
The original ByteChannel.read or the one you wrote?
k
both
m
Oh, ok. Then you won't need the suspendCoroutine thing.
What library is
ByteChannel
from?
Seems weird to me that a suspending function has a callback as a parameter
k
kotlin.coroutines.io.ByteReadChannel#read
e
I think the real question here is why are you doing a second nested launch if you just want to wait for the coroutine to complete before starting the next loop iteration?
k
I was doing that cause i didn't know how to do it otherwise
it's gone now
e
Alright, should be fine then. I assume that since
read
is a suspending function it will wait until new bytes come into the channel before writing out to the output channel.
c
What's your code look like now @Kroppeb?
message has been deleted