Skip to content

Latest commit

ย 

History

History
61 lines (42 loc) ยท 2.65 KB

0731-android.md

File metadata and controls

61 lines (42 loc) ยท 2.65 KB

2020.07.31

ViewModel

ViewModel ํด๋ž˜์Šค

  • ์ˆ˜๋ช… ์ฃผ๊ธฐ๋ฅผ ๊ณ ๋ คํ•˜์—ฌ UI๊ด€๋ จ ๋ฐ์ดํ„ฐ ์ €์žฅ ํ˜น์€ ๊ด€๋ฆฌ

  • ํ™”๋ฉด ํšŒ์ „์ฒ˜๋Ÿผ ๊ตฌ์„ฑ๋ณ€๊ฒฝ ์‹œ์—๋„ ๋ฐ์ดํ„ฐ๋ฅผ ์œ ์ง€ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•จ

  • ViewModel์„ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ์จ ํ•ด๊ฒฐ๋˜๋Š” ๋ฌธ์ œ๋“ค

    • ์‹œ์Šคํ…œ์—์„œ UI controller๋ฅผ ์ œ๊ฑฐํ•˜๊ฑฐ๋‚˜ ๋‹ค์‹œ ๋งŒ๋“ค ๊ฒฝ์šฐ, controller์— ์ €์žฅ๋˜์–ด ์žˆ๋˜ ๋ชจ๋“  UI ๊ด€๋ จ ๋ฐ์ดํ„ฐ๊ฐ€ ์†Œ์‹ค๋œ๋‹ค. ๊ตฌ์„ฑ ๋ณ€๊ฒฝ์„ ์œ„ํ•ด ์•กํ‹ฐ๋น„ํ‹ฐ๊ฐ€ ์žฌ์ƒ์„ฑ๋˜๋Š” ๊ฒฝ์šฐ ์‚ฌ์šฉ์ž ๋ชฉ๋ก์„ ๋‹ค์‹œ ๊ฐ€์ ธ์™€์•ผ ํ•œ๋‹ค. ๋ฐ์ดํ„ฐ๊ฐ€ ๋‹จ์ˆœํ•œ ๊ฒฝ์šฐ์—๋Š” onSaveInstanceState()๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ onCreate() ๋ฒˆ๋“ค์—์„œ ๋ณต์›ํ•  ์ˆ˜ ์žˆ์ง€๋งŒ, ์†Œ๋Ÿ‰์˜ ๋ฐ์ดํ„ฐ๋งŒ ํ•ด๋‹นํ•œ๋‹ค.
    • UI controller๋Š” ๋น„๋™๊ธฐ ํ˜ธ์ถœ์„ ๊ด€๋ฆฌํ•˜๋Š”๋ฐ ์—ฌ๊ธฐ์—๋Š” ๋งŽ์€ ์œ ์ง€๋ณด์ˆ˜๊ฐ€ ํ•„์š”ํ•˜๊ณ , ์ปดํฌ๋„ŒํŠธ ๋ณ€๊ฒฝ ์‹œ ๊ฐœ์ฒด๊ฐ€ ์žฌ์ƒ์„ฑ๋˜๋ฉด ๊ฐœ์ฒด๊ฐ€ ์ด๋ฏธ ์‹คํ–‰๋œ ํ˜ธ์ถœ์„ ๋‹ค์‹œ ํ•ด์•ผํ•˜๋Š” ์ผ์ด ์ƒ๊ธฐ๋Š”๋ฐ, ์—ฌ๊ธฐ์„œ ๋ฆฌ์†Œ์Šค์˜ ๋‚ญ๋น„๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.
    • UI controller์— ๋ฐ์ดํ„ฐ ๋กœ๋“œ๋ฅผ ๋‹ด๋‹นํ•˜๋ฉด ํด๋ž˜์Šค๊ฐ€ ํŒฝ์ฐฝ๋˜๊ณ , ํ…Œ์ŠคํŠธ๊ฐ€ ์–ด๋ ต๋‹ค.
  • Ui controller logic ์œผ๋กœ๋ถ€ํ„ฐ view data ์†Œ์œ ๊ถŒ์„ ๋ถ„๋ฆฌํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ๋ฐ”๋กœ ViewModel์ด๋‹ค.

  • ViewModel ๊ฐ์ฒด๋Š” ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋ณ€๊ฒฝ๋˜๋Š” ๋™์•ˆ, ์ž๋™์œผ๋กœ ๋ณด๊ด€๋œ๋‹ค. ๋”ฐ๋ผ์„œ ViewModel์ด ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๋ฐ์ดํ„ฐ๋Š” ๋‹ค์Œ Activity๋‚˜ fragment instance์—์„œ ์ฆ‰์‹œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

  • ๋‹ค์Œ์€ ์‚ฌ์šฉ์ž ๋ชฉ๋ก์ด๋ผ๋Š” ๋ฐ์ดํ„ฐ๋ฅผ activity/fragment ๋Œ€์‹  ViewModel์— ํ• ๋‹นํ•˜๋Š” ์ฝ”๋“œ์ด๋‹ค.

  •     class MyViewModel : ViewModel() {
            private val users: MutableLiveData<List<User>> by lazy {
                MutableLiveData().also {
                    loadUsers()
                }
            }
    
            fun getUsers(): LiveData<List<User>> {
                return users
            }
    
            private fun loadUsers() {
                // Do an asynchronous operation to fetch users.
            }
        }
        
  • ๋‹ค์Œ์€ activity์—์„œ ๋ชฉ๋ก(๋ฐ์ดํ„ฐ)์— ์ ‘๊ทผํ•˜๋Š” ์ฝ”๋“œ์ด๋‹ค.

  •     class MyActivity : AppCompatActivity() {
    
            override fun onCreate(savedInstanceState: Bundle?) {
                // Create a ViewModel the first time the system calls an activity's onCreate() method.
                // Re-created activities receive the same MyViewModel instance created by the first activity.
    
                // Use the 'by viewModels()' Kotlin property delegate
                // from the activity-ktx artifact
                val model: MyViewModel by viewModels()
                model.getUsers().observe(this, Observer<List<User>>{ users ->
                    // update UI
                })
            }
        }