【问题标题】:where object should be store in mvvm对象应该存储在 mvvm 中的位置
【发布时间】:2021-01-22 18:43:19
【问题描述】:

我不明白 mvvm 模型对象应该存储在哪里。 例如我有应用程序

class MainActivity : AppCompatActivity() {

    private lateinit var viewModel: MyViewModel


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

        viewModel = ViewModelProvider(this).get(MyViewModel::class.java)

        viewModel.userScore.observe(this, Observer { it->
            score_view.text = it.toString()
        })

        score_bt.setOnClickListener {
            viewModel.scorePoint()
        }

    }
}
class MyViewModel: ViewModel() {
    val _userScore = MutableLiveData<Int>()
    val userScore: LiveData<Int>
        get() = _userScore

    init {
        _userScore.value = 1
    }

   fun scorePoint(){
        _userScore.value = (_userScore.value)?.plus(1)
    }

}
class Game {
    val score = 0
}

当用户单击按钮时,分数会增加。我想将分数存储在对象类 Game 中。对象应该存储在哪里以及如何将对象与viewmodel连接起来,因为我认为viewmodel不应该包含对象。需要明确的是,我不希望在用户关闭应用程序时存储该对象。

【问题讨论】:

    标签: android kotlin mvvm


    【解决方案1】:

    对象游戏

    class Game {
        var score = 0
    }
    

    视图模型

    class MyViewModel: ViewModel() {
    
        val game = Game() //init the object
        val _userScore = MutableLiveData<Game>()
        val userScore: LiveData<Game>
            get() = _userScore
            
        init {
            _userScore.value = game.apply {
                score = 1
            }
        }
            
        fun scorePoint(){
            _userScore.value = game.apply {
                score++
            }
        }
    
    }
    

    【讨论】:

    • 当我实施你的建议时,我的 UI 不会更新编辑,我将`score.plus(1)` 更改为`score++` 并且它可以工作
    • @czlowiekzgon 我没有实际测试它,我已经编辑了答案
    猜你喜欢
    • 2010-12-18
    • 2023-03-10
    • 2020-08-02
    • 2023-03-31
    • 1970-01-01
    • 2010-10-21
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多