android開發(fā)的架構(gòu)經(jīng)歷了MVC、MVP、MVVM,三種架構(gòu)方式?jīng)]有好與差的區(qū)分,在實際的開發(fā)過程中因人而異,因項目而異。但是,最近幾年,隨著Google不斷對android的體系進行梳理,加之不斷推出的API。MVVM的模式越來越受到開發(fā)者的喜愛,而在MVVM的架構(gòu)中,很重要的一個組件就是我們今天的主角——ViewModel。
ViewModel的簡介
在頁面(Activity/Fragment)功能較為簡單的情況下,我們通常會將UI交互、與數(shù)據(jù)獲取等相關(guān)的業(yè)務(wù)邏輯全部寫在頁面中。但是在頁面功能復(fù)雜的情況下,代碼量會變的非常多,后期的維護和擴展非常的麻煩,這是典型的MVC的架構(gòu)模式。其實真正的在理想情況下,應(yīng)該是UI展示與數(shù)據(jù)處理分開,即各司其職。頁面(Activity/Fragment)只負責(zé)UI的展示,數(shù)據(jù)的處理由專門的類去實現(xiàn),而這個就是我們ViewModel的由來。
ViewModel可以這么理解: 它是介于View(視圖)和Model(數(shù)據(jù)模型)之間的一個東西。它起到了橋梁的作用,使視圖和數(shù)據(jù)既能分離,也能保持通信。即ViewModel 是以生命周期的方式存儲與管理UI相關(guān)數(shù)據(jù)。
ViewModel的作用
- 在MVVM模式中,使Model與View分離
- 存儲數(shù)據(jù)
- 負責(zé)為UI準(zhǔn)備數(shù)據(jù)
ViewModel的生命周期
這里有一張官網(wǎng)關(guān)于ViewModel的生命周期的圖

從這張圖中,我們不難看出:
(1)ViewModel的生命周期比Activity或者Fragment長,因此 ViewModel不能持有Context的對象,不然會出現(xiàn)內(nèi)存泄漏。
(2)Activity在生命周期中可能會觸發(fā)多次onCreate(),而ViewModel則只會在第一次onCreate()時創(chuàng)建,然后直到最后Activity銷毀。
ViewModel的基本使用
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
class UserModel : ViewModel() {
val userLiveData = MutableLiveData<User>()
init {
userLiveData.postValue(User(1, "jack"))
}
fun doSomething() {
val user = userLiveData.value?.apply {
age = (100..500).random()
name = "jack$age"
}
userLiveData.value = user
}
}
3.在Activity/Fragment中將ViewModel進行關(guān)聯(lián)
// Activity中的使用
class ViewModuleActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view_module)
// 獲取ViewModel實例
val userModel = ViewModelProvider(this).get(UserModel::class.java)
// 利用livedata實現(xiàn)雙向綁定
userModel.userLiveData.observe(this,
Observer<User> { t -> username.text = t.toString() })
user_change.setOnClickListener {
userModel.doSomething()
}
}
}
// Fragment中的使用
class DashboardFragment : Fragment() {
private lateinit var dashboardViewModel: DashboardViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
dashboardViewModel =
ViewModelProvider(this).get(DashboardViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_dashboard, container, false)
val textView: TextView = root.findViewById(R.id.text_dashboard)
dashboardViewModel.text.observe(viewLifecycleOwner, Observer {
textView.text = it
})
textView.setOnClickListener {
startActivity(Intent(activity,ViewModuleActivity::class.java))
}
return root
}
}
總結(jié):viewModel的使用相對來說比較簡單,它更多的是一種思想的體現(xiàn)。
ViewModel的其他注意事項
1.Fragment間共享數(shù)據(jù)
因為ViewModel只會在Activity存活時,會創(chuàng)建一次,因此在同一個Activity中可以在多個Fragment中共享ViewModel中數(shù)據(jù)。
public class FragmentA extends Fragment{
//...
ViewModelProviders.of(getActivity()).get(AViewModel.class).getDatas().observe(this, new Observer<User>() {
@Override
public void onChanged(@Nullable User user) {
//獲取Activity中數(shù)據(jù)變化
}
});
}
public class FragmentB extends Fragment{
//...
ViewModelProviders.of(getActivity()).get(AViewModel.class).getDatas().observe(this, new Observer<User>() {
@Override
public void onChanged(@Nullable User user) {
//獲取Activity中數(shù)據(jù)變化
}
});
}
//在Activity中更新數(shù)據(jù)
ViewModelProviders.of(getActivity()).get(AViewModel.class). updateUser();
2.ViewModel絕對不要持有下列引用
1.view
2.Lifecycle
3.其他任何可能持有Activity Context的類的引用
3.ViewModel中使用Context
如果ViewModel需要Applicaiton的Context(為了獲取系統(tǒng)服務(wù)),該如何處理?
自定義一個類,繼承自AndroidViewModel
構(gòu)造器一定要有一個唯一參數(shù)-Application'的對象
class UserModel(application: Application) : AndroidViewModel(application) {
val userLiveData = MutableLiveData<User>()
private var mApplication: Application? = null
init {
userLiveData.postValue(User(1, "jack"))
mApplication = application
}
fun doSomething() {
val user = userLiveData.value?.apply {
age = (100..500).random()
name = "jack$age"
}
userLiveData.value = user
Toast.makeText(mApplication?.applicationContext,"數(shù)據(jù)發(fā)生了改變",Toast.LENGTH_SHORT).show()
}
}