F
F
foonfyrick2020-09-24 12:34:23
Android
foonfyrick, 2020-09-24 12:34:23

Did the MVVM pattern properly segregate responsibilities?

I am training to write simple applications, but looking at other people, I noticed some differences in the implementation of the template, and the question arose, am I doing it right myself?

//синглтон LiveData

object MyLiveData:MutableLiveData<String>() {
    //получение значения из liveData
    fun takeValue()=value
    //записывание значения в liveData
    fun pushValue(string:String?){ value=string }
}

//Model

open class Model {
    protected open val dataBase:FirebaseDatabase= FirebaseDatabase.getInstance()
    protected open val myRef:DatabaseReference=dataBase.getReference("MVVMmessages")
    protected open val myLiveData=MyLiveData
    //получение сообщения из базы данных
    open fun getMessageFromDB(){
        myRef.addValueEventListener(object : ValueEventListener {
            override fun onCancelled(p0: DatabaseError) {}
            override fun onDataChange(p0: DataSnapshot) {
                myLiveData.pushValue(p0.getValue(String::class.java))
            }
        })
    }
    //внедрение значения в базу данных
    open fun pushMessageToDB(message:String?){
        myRef.setValue(message)
    }
}

//ViewModel

open class MyViewModel:ViewModel() {
    protected open val model= Model()
    protected open val myLiveData:MyLiveData=MyLiveData
    //получение значения из базы данных
    open fun getter(){
        model.getMessageFromDB()
    }
    //установка значения в базу данных
    open fun setter(){
        model.pushMessageToDB(myLiveData.takeValue())
    }
}

//View
open class MainActivity : AppCompatActivity() {
    protected open lateinit var myViewModel: MyViewModel
    protected open var myLiveData:MyLiveData=MyLiveData

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // установка наблюдателя
        myLiveData.observe(this, Observer { tvTextForObserver.text=it })
        myViewModel=ViewModelProvider(this).get(MyViewModel::class.java)
        //запись данных
        btn_push.setOnClickListener {
            myLiveData.pushValue(edText.text.toString())
            myViewModel.setter()
            edText.text.clear()
        }
        //получение данных
        btn_get.setOnClickListener {
            myViewModel.getter()
            tvText.text=myLiveData.takeValue()
        }
        btn_clear.setOnClickListener {
            tvText.text=""
            edText.text.clear()
        }
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question