I have state I want to share between `onStart` and...
# coroutines
d
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
But it's how flow works by default, just use
flow {}
block
👍🏼 1
1
e
Do this:
Copy code
fun <T> Flow<T>.myOperator() = flow {
    try {
         openResource()
         emitAll(this@myOperator)
    } finally {
         closeResource()
    }
}
👍🏼 4
b
@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
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
Yeah, actually it depends. thanks @gildor