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

bbaldino

05/20/2020, 11:03 PM
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

Adam Powell

05/20/2020, 11:53 PM
Expose a
Flow
as your extension instead:
Copy code
val Foo.incomingMyType: Flow<MyType> get() = incoming.receiveAsFlow()
    .map { MyType(it) }
b

bbaldino

05/20/2020, 11:55 PM
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

octylFractal

05/21/2020, 12:14 AM
it's not in 1.4, it's def. in 1.3, but maybe a later version
a

Adam Powell

05/21/2020, 12:14 AM
o

octylFractal

05/21/2020, 12:15 AM
since dec 2019 according to commits
a

Adam Powell

05/21/2020, 12:16 AM
you can declare a dependency on a newer
kotlinx-coroutines-core
version and ktor will happily still use it
b

bbaldino

05/21/2020, 4:29 AM
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

Orhan Tozan

05/28/2020, 6:43 PM
Why not use the latest stable version and use 1.3.7?
4 Views