Use of LiveData+ViewModel in JetPack

  • Let's start with JetPack:

    JepPack is a collection of Android Software Components launched by Google, which translates into a jetpack,
    With this framework, Google can fly you.
    It helps you follow best practices, frees you from the work of writing boilerplate code, and simplifies complex tasks so you can focus on the code you need.

    JetPck is mainly divided into four parts

    1: Foundation

    AppCompat,Android KTX,Multidex,Test

    2: Architecture

    Data Binding,LifeCycles,LiveData,ViewModel...

    3: behavior

    Download Manager,Media,Notification,Shareing...

    4: UI


    These four parts are excellent. Here I choose LiveData and ViewModel to do case analysis for you,
    It can automatically remember the data state before rotation, and automatically synchronize in real time


Notify view when underlying database changes


Manage interface related data in a lifecycle focused way

The above is the life cycle of viewmodel, which will automatically monitor the life cycle of activity. It only calls onCleared () when the activation city is completely destroyed. You can release the problem you need to release here.

    class SeekBarModel : ViewModel() {
    //Inherit ViewModel
    val _sBar = MutableLiveData<BarI>()

    val sBar: MutableLiveData<BarI>
        get() = _sBar

    var progress: Int? = null
        get() = _sBar?.value?.progress

    var observable: Subscription? = null
        get() = _sBar?.value?.observable

    override fun onCleared() {
        Log.d("SeekBarModel", "ViewModel-->Being destroyed")

class BarI(progress: Int, observable: Subscription?) {
    var progress: Int? = null
    var observable: Subscription? = null

    init {
        this.progress = progress
        this.observable = observable

class OriginLiveDataActivity : AppCompatActivity() {
    private lateinit var sekBarModel: SeekBarModel
    var observable: Subscription? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        sekBarModel = ViewModelProviders.of(this).get(
        sekBarModel.sBar.observe(this, Observer { data ->
            bar_life.progress = if (data == null) 0 else data.progress!!
            btn_life.text = "Current progress" + bar_life.progress
        btn_start.setOnClickListener { view ->

//One second plus one to display the progress bar on the bar
    private fun start() {
        if (sekBarModel.observable == null)
            observable = Observable
                    .interval(1000, TimeUnit.MILLISECONDS)
                    .subscribe {
                        bar_life.progress += 1
                        sekBarModel.sBar.postValue(BarI(bar_life.progress, observable!!))
                        if (bar_life.progress == 100)


Tags: Mobile Android Google emoji Database

Posted on Mon, 02 Dec 2019 06:51:03 -0800 by josh