Hi, I have a channel for offering packets: ```val ...
# android
l
Hi, I have a channel for offering packets:
Copy code
val responsePacketsChannel = ConflatedBroadcastChannel<ResponsePacket>()
ResponsePacket is a interface because I have multiple packets which I want to offer, e.g.
ParameterPacket: ResponsePacket
or
TimePacket: ResponsePacket
. Now I'm wondering what would be the proper way to differentiate between the specific packets when I start to observe them. My first thought was using
Pair<ResponsePacketType, ResponsePacket>
combined with an enum
ResponsePacketType
->
Copy code
val responsePacketsChannel = ConflatedBroadcastChannel<Pair<ResponsePacketType, ResponsePacket>>()
Is there maybe a better solution?
j
perhaps instead of interface a sealed class would be better in this case. You could then leverage where expression which forces you to exhaustively handle the various types and there you can delegate to to the specific code that handles the concrete type
l
I'm not sure if it's possible because all packets also inherit from a basic packet?!
z
Even if you don't use a sealed class (which I would also recommend, sealed classes can implement interfaces), you can still use a
when
on the actual packet type, which is much better than adding the abstraction of creating an enum to represent that. Enum doesn't add any type safety, and just creates more opportunities for bugs (eg incorrect mappings, more code to update for every change, etc).
l
@Zach Klippenstein (he/him) [MOD] The problem is that some of the packet implementations are huge and they all derive from a XModemPacket :
z
Not sure how size matters here. And your sealed class can extend XModemPacket.