简单聊聊Android和Flutter的ViewModel实现方案
Posted 小源子2016
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单聊聊Android和Flutter的ViewModel实现方案相关的知识,希望对你有一定的参考价值。
一.LiveData
public class DemoData extends LiveData<DemoData>
private int tag1;
private int tag2;
public int getTag1()
return tag1;
public void setTag1(int tag1)
this.tag1 = tag1;
postValue(this);
public int getTag2()
return tag2;
public void setTag2(int tag2)
this.tag2 = tag2;
postValue(this);
mDemoViewModel.getDemoData().observe(this, new Observer<DemoData>() //注册观察者,观察数据的变化
@Override
public void onChanged(DemoData demoData)
Log.e(TAG, "onChanged: 数据有更新");
);
二.MutableLiveData
1. ViewModel可以感知生命周期,当Activity销毁不至于出现问题
2.Fragment和Activity共享数据
3.ViewModel常常搭配LiveData使用
public class DemoViewModel extends ViewModel
// TODO: Implement the ViewModel
private MutableLiveData<String> myString = new MutableLiveData<>();
public MutableLiveData<String> getMyString()
return myString;
public void setMyString(String string)
this.myString.setValue(string);
mDemoViewModel = ViewModelProvider(this).get(DemoViewModel::class.java)
mDemoViewModel.getMyString().observe(this, new Observer<String>() //注册观察者
@Override
public void onChanged(String s)
Log.e(TAG, "onChanged: 值有变化="+s);
);
三.Flutter
Flutte订阅者可以是Provider ,其内部主要根据InheritedWidget将依赖关联的Widget再同步更新
class MainViewModel extends ChangeNotifier
四. 自定义
interface DataModelObserver
fun onCountUpdate(newCount: Int)
/**
* A singleton/observable data model for the data shared between Flutter and the host platform.
*
* This is the definitive source of truth for all data.
*/
class DataModel
companion object
val instance = DataModel()
private val observers = mutableListOf<WeakReference<DataModelObserver>>()
public var counter = 0
set(value)
field = value
for (observer in observers)
observer.get()?.onCountUpdate(value)
fun addObserver(observer: DataModelObserver)
observers.add(WeakReference(observer))
fun removeObserver(observer: DataModelObserver)
val iterator = observers.iterator();
while (iterator.hasNext())
val next = iterator.next();
if (next.get() == null || next.get() == observer)
observers.remove(next)
五.总结
1.由此看来,MVVM中的ViewModel层关键在于创建一个可观察对象,我想这应该也算响应式编程,
2.Flutter UI层面则是彻底的响应式,其展示依赖数据和框架层处理
3.android UI结合LiveData,则也可以监听数据变化从而数据UI,也就是随着数据的变化UI发生变化
六.参考
Android开发 LiveData与MutableLiveData详解
以上是关于简单聊聊Android和Flutter的ViewModel实现方案的主要内容,如果未能解决你的问题,请参考以下文章
简单聊聊Android和Flutter的ViewModel实现方案
简单聊聊Android和Flutter的ViewModel实现方案
WeexRN还是Flutter?聊聊阿里跨平台开发框架选型思路