Say I've got a class `Foo` (which I don't control)...
# coroutines
b
Say I've got a class
Foo
(which I don't control) which exposes a field
incoming: ReceiveChannel<String>
, and I have a custom type
data class MyType(val str: String)
and I want to add an extension field to
Foo
to expose a field
incomingMyType: ReceiveChannel<MyType>
. What's the best way to wrap the existing channel and map it to produce instances of
MyType
containing the
String
values? I have something equivalent to the code below working, but wondering if there's any better way. Maybe something with
Flow
?
Copy code
val Foo.incomingMyType: ReceiveChannel<MyType>
    get() = produce {
        for (str in incoming) {
            send(MyType(str))
        }
    }
a
Expose a
Flow
as your extension instead:
Copy code
val Foo.incomingMyType: Flow<MyType> get() = incoming.receiveAsFlow()
    .map { MyType(it) }
b
Is
receiveAsFlow
pretty new? I don't seem to have it
I'm on kotlinx-coroutines-core 1.3.3 looks like
Looks like it might be in 1.4...I'm doing this in ktor which is still on coroutines 1.3
But good to know...is there a better way than mine in the meantime? (Until I get
receiveAsFlow
?)
o
it's not in 1.4, it's def. in 1.3, but maybe a later version
a
o
since dec 2019 according to commits
a
you can declare a dependency on a newer
kotlinx-coroutines-core
version and ktor will happily still use it
b
Thanks, yeah looks like I was off by one (1.3.3 vs 1.3.4). Explicitly depending on 1.3.4 got it.
o
Why not use the latest stable version and use 1.3.7?