LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services.
The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.
// LoginFragment.onViewCreated Log.e("TTAG", "from LoginFragment, the init liveData is: ${LoginLiveData.get().value}") LoginLiveData.get().observe(viewLifecycleOwner, Observer { Log.e("TTAG", "from LoginFragment, the liveData changed: $it") }) Handler().postDelayed({ LoginLiveData.get().apply { value = LoginInfo("login", "login", "login@qq.com") } }, 2000)
// WelcomeFragment.onViewCreated Log.e("TTAG", "from LoginFragment, the init liveData is: ${LoginLiveData.get().value}") LoginLiveData.get().observe(viewLifecycleOwner, Observer { Log.e("TTAG", "from LoginFragment, the liveData changed: $it") }) Handler().postDelayed({ LoginLiveData.get().apply { value = LoginInfo("login", "login", "login@qq.com") } }, 2000)
日志
1 2 3 4 5 6 7
# 首次进入welcome E/TTAG: from WelcomeFragment, the init liveData is: null E/TTAG: from WelcomeFragment, the liveData changed:LoginInfo(account=welcome, pwd=welcome, email=welcome@qq.com) # 点击进入login E/TTAG: from LoginFragment, the init liveData is: LoginInfo(account=welcome, pwd=welcome, email=welcome@qq.com) E/TTAG: from LoginFragment, the liveData changed: LoginInfo(account=welcome, pwd=welcome, email=welcome@qq.com) E/TTAG: from LoginFragment, the liveData changed: LoginInfo(account=login, pwd=login, email=login@qq.com)