Android Jetpack
Android LiveData - 2 (ViewModel + LiveData)
----___<<<<<
2022. 1. 2. 15:26
이 글에서 Livedata에 대해 잠시 봤는데, 이 것을 ViewModel을 이용해서 한번 보겠습니다.
아래와 같이 ViewModel을 만들어줍니다.
그냥 단순하게, Livedata부분을 ViewModel로 옮겨준 것이라고 생각하면 됩니다.

코드는 아래와 같이 ViewModel을 만들어서 파일 밖으로 빼줬습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainActivityViewModel : ViewModel() { | |
var count = MutableLiveData<Int>() | |
init { | |
count.value = 0 | |
} | |
fun updateCount(){ | |
count.value = (count.value)?.plus(1) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainActivity : AppCompatActivity() { | |
private lateinit var binding: ActivityMainBinding | |
private lateinit var viewModel: MainActivityViewModel | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
binding = DataBindingUtil.setContentView(this, R.layout.activity_main) | |
viewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java) | |
viewModel.count.observe(this, Observer { | |
binding.countText.text = it.toString() | |
}) | |
binding.button.setOnClickListener { | |
viewModel.updateCount() | |
} | |
} | |
} |
자, 계속해서 다음 글에서 LiveData에 더 알아보도록 하겠습니다.