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

Dominaezzz

10/16/2019, 10:51 AM
I have state I want to share between
onStart
and
onCompletion
of a
Flow
. (Basically open a resource in
onStart
and close it in
onCompletion
) What's the most idiomatic way besides reinventing the wheel?
g

gildor

10/16/2019, 12:21 PM
But it's how flow works by default, just use
flow {}
block
👍🏼 1
1
e

elizarov

10/16/2019, 1:10 PM
Do this:
Copy code
fun <T> Flow<T>.myOperator() = flow {
    try {
         openResource()
         emitAll(this@myOperator)
    } finally {
         closeResource()
    }
}
👍🏼 4
b

bnn

10/17/2019, 1:05 AM
@elizarov Is it the case when it comes to
channelFlow
?
(I asked this question because usually I use channelFlow to wrap callback based api, creating callback object inside
channelFlow {}
block and closing it in
awaitClose {}
)
g

gildor

10/17/2019, 1:39 AM
For callbacks yes, use channelFlow/callbackFlow, but this question not about callbacks, as I understand,
awaitClose
tho of course useful, but actual implementation depends on what is happening after
onStart
b

bnn

10/17/2019, 2:45 PM
Yeah, actually it depends. thanks @gildor
6 Views