How would y'all register a callback on an element ...
# coroutines
r
How would y'all register a callback on an element getting passed along in a
Flow
(think
Flow<Card>
) - the callback should fire after the card has been disconnected. I'm currently on
interface Card { var afterCardRemoval: Function<Unit>? }
and then firing from the scope producing the
Flow<Card>
, but that feels kinda dirty.
j
I don't think I understand the question. What does the flow have to do with the question? Are you asking about how to register the callback or how to fire it? For instance, why doesn't
.onEach { afterCardRemoval = { ... } }
work for you?
r
Are you sure it wouldn't work better as a Flow<Event> where Event can be CardDetected, CardRemoved etc?
r
https://kotlinlang.slack.com/archives/C1CFAFJSK/p1657876089729049?thread_ts=1657875875.988959&amp;cid=C1CFAFJSK That was my first approach as well, but I was wondering if I could associate it by callback instead of the consuming application having to do the association
... how do you even reply to specific replies in slack?
For instance, why doesn't .onEach { afterCardRemoval = { ... } } work for you?
there's basically the
Flow<Event>
which I'm processing, and I'm wondering if I can change the API a bit.
r
Yeah, unfortunately it's pretty application specific what makes the most sense for your consuming code but I agree callbacks feel a little clumsy when you're already working with coroutines
Another option would be to add a Lifecycle flow inside Card which they could subscribe to separately
r
That's an option, is there one which I can use to send a single value, then finishes?
r
A StateFlow might work well here because it means if I ever have a Card from anywhere I can always check if the current state is Active or Removed, as well as the original use case of listening for removal
r
I've tried with a
MutableStateFlow
, but there's a) how do I clean it up, aka how do I set the
Flow
from the state to over? Make it a
take()
is my current approach, but I'm not sure I like it. Also, how do I fire off an
async
into the sunset? the
coroutineScope { async { flow.collect { ... } } }
doesn't yield as I'd expect it to.
g
If you want Flow over just cancel it (or use operators like first()/until() which will close it on some event You cannot cancel MutableStateFlow btw, so it's not probably what you beed
Also flow implementation itself can cancel itself after some event