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

Rohan Maity

08/08/2020, 3:20 PM
I am using BroadcastChannel as Flow But it is not receiving anything in collect
Copy code
tunnel.pipe.send("LOPI")

            tunnel.pipe.asFlow().flowOn(Dispatchers.Main).collect {

                tvPUI.text = it.toString()
            }

            delay(2000)

            tunnel.pipe.send("HOLA")
t

tseisel

08/08/2020, 3:43 PM
collect
suspends until the source channel is closed, therefore "HOLA" could not be sent
r

Rohan Maity

08/08/2020, 3:44 PM
Ok so If I wanna use it as Hot observable do I have to some other way ?
AFAIU BroadcastChannel could be used as PublishSubject
w

wasyl

08/08/2020, 3:49 PM
You can use it like this, just launch the collection in a separate coroutine (
launch { ..collect { } }
)
r

Rohan Maity

08/08/2020, 3:54 PM
yes It is working 🙂
But quite still ambiguous why ?
Is it because when I did the first
send
and since its suspend function that whole coroutine was suspended (including collection)
and it was awaiting for collection
but then there was no collection since it was kinda suspended forever ?
w

wasyl

08/08/2020, 3:56 PM
When you launch a single coroutine, it runs whatever is inside sequentially.
collect { }
starts collecting the flow and only completes (returns) when the flow finishes (channel closes). But the new coroutine started with
launch
runs concurrently, so
launch { }
call returns immediately, allowing your
send
to be actually called
But, with the other
launch
do you receive
tunnel.pipe.send("LOPI")
? Because I’m not sure you should, as you send it before flow is collected, and channels are hot, which means
LOPI
should be lost
r

Rohan Maity

08/08/2020, 4:18 PM
no, I did not. and that is what I was expecting it
thanks @wasyl 😄
👍 1
d

darkmoon_uk

08/08/2020, 11:50 PM
Just to clarify - even putting the underlying implementations aside - your example shows a conceptual gap: "LOPI" should be 'lost' as a Flow is hot and there's no receiver at that point.
r

Rohan Maity

08/09/2020, 5:47 AM
flow is cold as far as I have read in medium articles Its channel what are hot I intended that "LOPI" should be lost as well
So when I used
send "LOPI"
(which is suspend) and since I also tried collection in same coroutine. and there was no receiver for "LOPI" that whole coroutine was suspended therefore collection was never completed in first place
4 Views