androidandroid-mvp

MVP with ViewModel component


Disclaimer: This is not a MVP vs MVVM post.

I've made a simple project to see how MVP works

My Activity:

class MainActivity : AppCompatActivity(), MainContract.View {

    lateinit var presenter: MainPresenter
    private val counter by lazy { findViewById<TextView>(R.id.value_tv) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        presenter = MainPresenter(this)

        increment_value_btn.setOnClickListener {
            presenter.incrementCount()
        }

        decrement_value_btn.setOnClickListener {
            presenter.decrementCount()
        }

    }

    override fun updateCount(count: Int) {
        counter.text = count.toString()
    }
}

My Presenter:

class MainPresenter(mainView: View) : Presenter {

    var view: View = mainView
    var counter: Int = 0

    override fun incrementCount() {
        counter++
        view.updateCount(counter)
    }

    override fun decrementCount() {
        counter--
        view.updateCount(counter)
    }

}

When configurations changes (orientation) my number is reset. I know it's a normal behaviour as the activity is dropped and re-created. I've read that viewmodel is designed to help the data survives. However I don't know how to implement it with my presenter.


Solution

  • In the end I reworked my application and decided to go directly with MVVM and followed this course