Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

android - where object should be store in mvvm

I dont understand where in mvvm model object should be store. For e.g i have app

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
}

when user click button the score increase. I want to store the score in object class Game. Where should the object be stored and how to connect the object with viewmodel, because I think that viewmodel shouldn't contain the object. To be clear I don't expect to stored that object when user turn off app.

question from:https://stackoverflow.com/questions/65850979/where-object-should-be-store-in-mvvm

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Object Game

class Game {
    var score = 0
}

The ViewModel

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++
        }
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...