[英]where object should be store in mvvm
我不明白 mvvm model object 應該存儲在哪里。 例如我有應用程序
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
}
當用戶單擊按鈕時,分數會增加。 我想將分數存儲在 object class 游戲中。 object 應該存儲在哪里以及如何將 object 與 viewmodel 連接,因為我認為 viewmodel 不應該包含 object。 需要明確的是,當用戶關閉應用程序時,我不希望存儲 object。
Object 游戲
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++
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.