简体   繁体   中英

Bluetooth SPP + Android MVVM + Coroutines

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

You don't need LiveData everywhere, Only use it if you have to observe it or update the UI continuously like you want to use it in the variable when you have to take live data from the UI like editText. You can use liveData everywhere in your project, it is up to you whether you want to use it or not, I recommend that you have to look for the necessity when choosing it.

You are correct about the readByteArray as it is a source of data that we are using, so it is considered as a repository in MVVM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM