附上官網鏈接:https://developer.android.google.cn/topic/libraries/architecture/viewmodel
ViewModel簡介
該ViewModel
類被設計用來存儲和管理UI界面相關的數據生命周期中的意識的方式。ViewModel
類允許生存數據配置更改,如屏幕旋轉。
存在的意義 (解決痛點)
1. 數據的持久化
eg: 當系統銷毀或重新創建UI控制器(Activity
、fragment
、View
等),則您存儲在其中的所有與UI相關的瞬時數據都將丟失。
activity
的onSaveInstanceState()
機制可以用來保存和恢復數據。
缺點:此方法僅適用于可以先序列化然后反序列化的少量數據,不適用于潛在的大量數據,例如用戶列表或位圖。
生命周期.png
的ViewModel
生命周期可以看到,它的生命周期橫跨Activity
的所有生命周期,包括旋轉等出現的重新創建的生命周期,直到 Activity
真正意義上銷毀后才會結束。這樣子數據存儲在ViewModel
中時,便可以保證在生命周期中數據不會丟失
2. UI控制器(Activity、fragment等)異步調用,導致的潛在內存泄漏
面對請求網絡、讀取IO、或者操作數據庫等異步操作,有些操作相當耗時,在UI控制器中我們設置這些回調等待結果,有可能在UI控制器銷毀的時候才返回。
在ViewModel
中處理數據的回調,當Activity
銷毀的時候,ViewModel
也會跑onCleared()清理數據 這樣子就不會存在Activity
內存泄漏的問題。
3.分擔UI控制器的負擔
類似MVP中的P層,MVVM中VM存在意義就是替UI 控制器減輕負擔。UI控制器只用于相應用戶操作,展示數據,將具體的數據邏輯操作(eg:加載網絡、數據庫數據...等)放到VM層做處理。分工更加明確,也方便測試。
4.在Fragment之間共享數據
比如Activity
在兩或多個Fragment
中,你使用一個Fragment
跟另外的Fragment
通信,常見的操作是定義接口在Activity
中根據接口返回邏輯調用到另外的Fragmet
,也有其他可以用EventBus 廣播
等其它的處理方式,但是前者耦合度高,后者也是相對繁瑣
在ViewModel
中,你可以獲取同一個Activity綁定的ViewModel
并監聽數據的變化 進而實現通信 下面是官網的例子
class SharedViewModel : ViewModel() {
val selected = MutableLiveData<Item>()
fun select(item: Item) {
selected.value = item
}
}
class MasterFragment : Fragment() {
private lateinit var itemSelector: Selector
private lateinit var model: SharedViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
model = activity?.run {
ViewModelProviders.of(this)[SharedViewModel::class.java]
} ?: throw Exception("Invalid Activity")
itemSelector.setOnClickListener { item ->
// Update the UI
}
}
}
class DetailFragment : Fragment() {
private lateinit var model: SharedViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
model = activity?.run {
ViewModelProviders.of(this)[SharedViewModel::class.java]
} ?: throw Exception("Invalid Activity")
model.selected.observe(this, Observer<Item> { item ->
// Update the UI
})
}
}
好處:
-
Activity
不需要知道兩者間的交互也不需要做什么,解耦 -
Fragment
不需要判斷對方是否存在等問題,也不需要持有對方的引用,不影響本身的任何工作,對其生命周期無感。
重點關注的點!!!
在ViewModel中不要持有Activity的引用
在ViewModel中不要持有Activity的引用
在ViewModel中不要持有Activity的引用
(重要的事情說三遍,因為生命周期比Activity略長 會導致Activity被挾持!!!)
如果需要context
對象,可以自行導入Application
的context
官方也提供一個含有context
的ViewModel
的子類,AndroidViewModel
你可以直接繼承它
public class AndroidViewModel extends ViewModel {
@SuppressLint("StaticFieldLeak")
private Application mApplication;
public AndroidViewModel(@NonNull Application application) {
mApplication = application;
}
/**
* Return the application.
*/
@SuppressWarnings({"TypeParameterUnusedInFormals", "unchecked"})
@NonNull
public <T extends Application> T getApplication() {
return (T) mApplication;
}
}
簡單使用
- 導入庫
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:${var}"
- 創建子類繼承
ViewModel()
的
class NameViewModel :ViewModel(){
// 創建Livedata的字符串
val currencyName : MutableLiveData<String> = MutableLiveData()
val totalMemory : MutableLiveData<String> = MutableLiveData()
val remainMemory : MutableLiveData<String> = MutableLiveData()
}
- Activity中使用
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
//1.先獲取一個ViewModel對象
val mViewModel = ViewModelProviders.of(this).get(NameViewModel::class.java)
//2.定義一個觀察者
val nameObserver = Observer<String> { newName ->
name_text.text = newName
}
//3.通過使用ViewModel對象進行監聽
mViewModel.currencyName.observe(this, nameObserver)
}
上面的展示了最基本的使用方式,先獲取到
mViewModel
對象,然后ViewModel.currencyName.observe(this, nameObserver)
進行監聽Observer<String> { newName -> name_text.text = newName }
當數據改變的時候,便會回調監聽的內容,并且傳入新的newName
的值
基礎封裝
下面對基本項目上用到的ViewModel
進行基本的封裝
先封裝 BaseViewModel
BaseActivity
(以下的封裝只涉及ViewModel
,基本的類根據自己的需求進行其他的封裝)
BaseViewModel
open class BaseViewModel :ViewModel(){
//處理異常
val mException:MutableLiveData<Throwable> = MutableLiveData()
}
BaseActivity
open class BaseActivity<VM:BaseViewModel> : AppCompatActivity(), LifecycleObserver {
lateinit var mViewModel: VM
override fun onCreate(savedInstanceState: Bundle?) {
initVM()
super.onCreate(savedInstanceState)
startObserver()
}
open fun startObserver(){
}
open fun providerVMClass():Class<VM>? = null
private fun initVM() {
providerVMClass()?.let {
mViewModel = ViewModelProviders.of(this).get(it)
}
}
}
使用:
class MainActivity : BaseActivity<NameViewModel>() {
//提供 NameViewModel
override fun providerVMClass(): Class<NameViewModel>? = NameViewModel::class.java
val job = Job()
val ioScope = CoroutineScope(Dispatchers.IO + job)
var licycleObserver = MyObserver()
companion object {
val TAG = "memory"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_mvvm2)
initViewModel()
btn1.setOnClickListener {
ioScope.launch {
withContext(Dispatchers.Main) {
mViewModel.remainMemory.value = "沒有cancel的"
}
}
}
}
private fun initViewModel() {
//獲取viewmodel
mViewModel = ViewModelProviders.of(this).get(NameViewModel::class.java)
//創建監聽 更新UI
val nameObserver = Observer<String> { newName ->
name_text.text = newName
}
val memoryObserver = Observer<String> { totalMemory ->
total_memory.text = totalMemory
}
val remainMemoryObserver = Observer<String> { remainMemory ->
remain_memory.text = remainMemory
}
mViewModel.currencyName.observe(this, nameObserver)
mViewModel.totalMemory.observe(this, memoryObserver)
mViewModel.remainMemory.observe(this, remainMemoryObserver)
}
}
構造器有參數的ViewModel
當ViewModel
構造函數帶有參數的時候,就不能像上面那種實例化,而是要借助ViewModelProvider
的Fatory
進行實例化
對上面的ViewModel
基礎使用改動一波
class NameViewModel(val currencyName:MutableLiveData<String>) :BaseViewModel(){
// 創建Livedata的字符串
val totalMemory : MutableLiveData<String> = MutableLiveData()
val remainMemory : MutableLiveData<String> = MutableLiveData()
// 創建工廠對象類
class NameViewModelFactory(private val current:MutableLiveData<String>):ViewModelProvider.NewInstanceFactory(){
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return NameViewModel(current) as T
}
}
}
使用 獲取一個ViewModel對象
//1.先獲取一個ViewModel對象
ViewModelProviders.of(this,NameViewModel.NameViewModelFactory(MutableLiveData("total"))).get(NameViewModel::class.java)
相比第一次獲取實例的方式是調用了ViewModelProvider of(@NonNull FragmentActivity activity, @Nullable Factory factory)
增加多了一個工廠對象其它的數據監聽跟基本的不帶參數實例化ViewModel
的用法一致
源碼跟蹤解讀
從最開始的ViewModelProviders.of
開始追蹤
從上圖可以看到
ViewModelProviders
主要是用于生成跟返回實例化的ViewModelProvider
對象的。看最本篇文章簡單在
Activity
中使用的時候
val mViewModel = ViewModelProviders.of(this).get(NameViewModel::class.java)
調用了
public class ViewModelProviders {
//...省略其他方法
//關鍵代碼1:
@NonNull
@MainThread
public static ViewModelProvider of(@NonNull FragmentActivity activity) {
return of(activity, null);
}
//關鍵代碼2:
@NonNull
@MainThread
public static ViewModelProvider of(@NonNull FragmentActivity activity,
@Nullable Factory factory) {
//關鍵代碼3:
Application application = checkApplication(activity);
if (factory == null) {
//關鍵代碼5
factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
}
//關鍵代碼6
return new ViewModelProvider(activity.getViewModelStore(), factory);
}
//關鍵代碼4:
private static Application checkApplication(Activity activity) {
Application application = activity.getApplication();
if (application == null) {
throw new IllegalStateException("Your activity/fragment is not yet attached to "
+ "Application. You can't request ViewModel before onCreate call.");
}
return application;
}
//關鍵代碼7
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
if (AndroidViewModel.class.isAssignableFrom(modelClass)) {
//noinspection TryWithIdenticalCatches
try {
return modelClass.getConstructor(Application.class).newInstance(mApplication);
} catch (NoSuchMethodException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
} catch (InstantiationException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
} catch (InvocationTargetException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
}
}
return super.create(modelClass);
}
}
可以看到在關鍵代碼2的方法中先是對Activity
進行Application
判空邏輯(關鍵代碼4 ),我們傳進來的factory
是空的,則ViewModelProvider.AndroidViewModelFactory.getInstance(application)
(關鍵代碼5)獲得一個factory
,再調用 關鍵代碼6 進而返回一個ViewModelProvider
關鍵代碼7 我們傳進來的ViewModel
類通過反射的形式創建ViewModel
對象并返回
先跟蹤關鍵代碼5進去看看factory
是怎么來的
public static class AndroidViewModelFactory extends ViewModelProvider.NewInstanceFactory {
private static AndroidViewModelFactory sInstance;
public static AndroidViewModelFactory getInstance(@NonNull Application application) {
if (sInstance == null) {
sInstance = new AndroidViewModelFactory(application);
}
return sInstance;
}
}
這里返回了一個單例對象AndroidViewModelFactory
返回上面的 關鍵代碼6 return new ViewModelProvider(activity.getViewModelStore(), factory);
跟蹤一下
public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
mFactory = factory;
mViewModelStore = store;
}
這里將mViewModelStore
跟mFactory
實例化了
mViewModelStore
是從activity.getViewModelStore()
得到的
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
public ViewModelStore getViewModelStore() {
if (getApplication() == null) {
throw new IllegalStateException("Your activity is not yet attached to the "
+ "Application instance. You can't request ViewModel before onCreate call.");
}
if (mViewModelStore == null) {
//先獲取是否存在`ViewModelStore`
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
if (nc != null) {
// Restore the ViewModelStore from NonConfigurationInstances
mViewModelStore = nc.viewModelStore;
}
if (mViewModelStore == null) {
//這里新建了`ViewModelStore`
mViewModelStore = new ViewModelStore();
}
}
return mViewModelStore;
}
}
看到上面已經生成了ViewModelStore
接下來跟蹤一下 ViewModelProviders.of(this).get(NameViewModel::class.java)
的get()
方法看看
public class ViewModelProvider {
private static final String DEFAULT_KEY =
"androidx.lifecycle.ViewModelProvider.DefaultKey";
@NonNull
@MainThread
public <T extends ViewModel> T get(@NonNull Class<T> modelClass) {
String canonicalName = modelClass.getCanonicalName();
if (canonicalName == null) {
throw new IllegalArgumentException("Local and anonymous classes can not be ViewModels");
}
return get(DEFAULT_KEY + ":" + canonicalName, modelClass);
}
public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
ViewModel viewModel = mViewModelStore.get(key);
if (modelClass.isInstance(viewModel)) {
if (mFactory instanceof OnRequeryFactory) {
((OnRequeryFactory) mFactory).onRequery(viewModel);
}
return (T) viewModel;
} else {
//noinspection StatementWithEmptyBody
if (viewModel != null) {
// TODO: log a warning.
}
}
if (mFactory instanceof KeyedFactory) {
viewModel = ((KeyedFactory) (mFactory)).create(key, modelClass);
} else {
viewModel = (mFactory).create(modelClass);
}
mViewModelStore.put(key, viewModel);
return (T) viewModel;
}
}
上面的代碼解釋一下:先從mViewModelStore.get(key);
獲取出來ViewModel,如果有則返回,沒有的話就調用之前擁有的工廠對象mFactory
類去viewModel = (mFactory).create(modelClass)
或者((KeyedFactory) (mFactory)).create(key, modelClass)
,最終調用mViewModelStore.put(key, viewModel);
public class ViewModelStore {
private final HashMap<String, ViewModel> mMap = new HashMap<>();
final void put(String key, ViewModel viewModel) {
ViewModel oldViewModel = mMap.put(key, viewModel);
if (oldViewModel != null) {
oldViewModel.onCleared();
}
}
final ViewModel get(String key) {
return mMap.get(key);
}
Set<String> keys() {
return new HashSet<>(mMap.keySet());
}
public final void clear() {
for (ViewModel vm : mMap.values()) {
vm.clear();
}
mMap.clear();
}
}
看到上面的代碼了嗎?
最終返回的viewModel
,返回前先調用了mViewModelStore.put(key, viewModel)
將這個
viewModel
存到mViewModelStore
中的HashMap
既然mViewModelStore
是存儲ViewModel
的地方 那我們也看一下ViewModelStore
中的clear()
是在哪里被調用的
我們跟蹤一下
ComponentActivity
的
getLifecycle().addObserver(new LifecycleEventObserver() {
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_DESTROY) {
if (!isChangingConfigurations()) {
getViewModelStore().clear();
}
}
}
});
上面可以看到在Lifecycle.Event.ON_DESTROY
為的狀態時調用getViewModelStore().clear();
方法。也就說在Activity
的生命周期到onDestory
的時候將本Activity
所有的ViewmModel
清除掉
這篇文章只是對基本的使用到這個調用的開始到結束,進行源碼的一個追蹤,對
ViewModel
有個比較深刻的印象,里面還有很多細節可以考究,只是本人技術有限,如果讀者有沒什么疑問可以在評論中說一下~