I'm creating an app to communicate with an external device through bluetooth, the connection is with serial protocol (rfcomm). Fortunately I found a good lib on GitHub named BlueFlow written completely in Kotlin and coroutines. I want to implement the MVVM pattern suggested in the android dev portal but I can't figure which is the right role of the bluetooth.
I have a base activity and a fragment where I want to manage the ui components and I want to update the text fields of the ui using data binding.
I think I need to create a variable in the ViewModel of type LiveData and Observe it in the fragment for changes.
The bluetooth library has a singleton class that I instantiate in the ViewModel and I need to pass it a context. The bluetooth class has a function for read incoming data "readByteArray" and it returns a Flow<ByteArray>
. I suppose this is the "Remote Data Source" in the MVVM architecture, am I right? Then I need to build a repository on top of it. Here there's the first stumbling block, how can I use the function readByteArray here? I can not use the singleton without pass a context and I think is not good to use context in this part of the architecture.
I also wrote a model class for the data received and it's like:
@Parcelize
data class IncomingResult(
@SerializedName("battery")
val battery: Int,
@SerializedName("sensor_one")
val sensorOne: Int,
@SerializedName("sensor_two")
val sensorTwo: Int,
): Parcelable
I need this class because sometimes I have to save these data into a room database.
I really appreciate any help/suggestion. I'm struggling with this problem from a week without find a solution. This is how I thought MVVM should be implemented in my project but I'm not sure it's correct:
Fragment
|
|
ViewModel
|
|
Repository
|
__________ | _________
| |
| |
Room Database Bluetooth
incoming data
question from:
https://stackoverflow.com/questions/65911264/bluetooth-spp-android-mvvm-coroutines 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…