Adnroid Lifecycle管理组件生命周期 && LiveData && ViewModel
Lifecycle 组件指的是 android.arch.lifecycle 包下提供的各种类与接口,可以让开发者构建能感知其他组件(主要指Activity 、Fragment)生命周期(lifecycle-aware)的类。
其中 Lifecycle 使用两个主要的枚举类来表示其所关联组件的生命周期:
- Event 事件 从组件或者Lifecycle类分发出来的生命周期,它们和Activity/Fragment生命周期的事件一一对应。(ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DESTROY);
- State 状态 当前组件的生命周期状态(INITIALIZED, DESTROYED, CREATED, STARTED, RESUMED)。
![](https://img2018.cnblogs.com/blog/1100100/201912/1100100-20191226172147079-98208849.png)
添加依赖配置:
def lifecycle_version = "1.1.1" // ViewModel and LiveData implementation "android.arch.lifecycle:extensions:$lifecycle_version" // alternatively - just ViewModel implementation "android.arch.lifecycle:viewmodel:$lifecycle_version" // use -ktx for Kotlin // alternatively - just LiveData implementation "android.arch.lifecycle:livedata:$lifecycle_version" // alternatively - Lifecycles only (no ViewModel or LiveData). // Support library depends on this lightweight import implementation "android.arch.lifecycle:runtime:$lifecycle_version" annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version" // alternately - if using Java8, use the following instead of compiler implementation "android.arch.lifecycle:common-java8:$lifecycle_version" // optional - ReactiveStreams support for LiveData implementation "android.arch.lifecycle:reactivestreams:$lifecycle_version"
使用:
package com.loaderman.architecturecomponents; import androidx.annotation.NonNull; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.LifecycleObserver; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.OnLifecycleEvent; public interface IPresenter extends LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) void onCreate(@NonNull LifecycleOwner owner); @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) void onResume(@NonNull LifecycleOwner owner); @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) void onPause(@NonNull LifecycleOwner owner); @OnLifecycleEvent(Lifecycle.Event.ON_STOP) void onStop(@NonNull LifecycleOwner owner); @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) void onDestroy(@NonNull LifecycleOwner owner); }
package com.loaderman.architecturecomponents; import android.util.Log; public class Model { private static final String TAG = "Model"; public static void startWork() { Log.d(TAG,"startWork"); } public static void endWork() { Log.d(TAG,"endWork"); } }
package com.loaderman.architecturecomponents; import android.content.Context; import android.util.Log; import androidx.annotation.NonNull; import androidx.lifecycle.LifecycleOwner; public class Presenter implements IPresenter { private static final String TAG = "Presenter"; private Model model = new Model(); private Context context; public Presenter(Context context) { this.context = context; } public void doWork(){ model.startWork(); } /** * 绑定远程服务 */ private void bindService(){ Log.d(TAG,"bindService"); } /** * 解绑远程服务 */ private void unbindService(){ Log.d(TAG,"unbindService"); } /** * 比如注册动态广播等操作可以转移到Presenter中,进一步降低Activity的复杂性 */ private void register(){ // context.registerReceiver(null,null); } private void unregister(){ // context.unregisterReceiver(null); } /** * 创建资源等 * @param owner */ @Override public void onCreate(@NonNull LifecycleOwner owner) { Log.e(TAG,"onCreate"); register(); bindService(); } @Override public void onResume(@NonNull LifecycleOwner owner) { } @Override public void onPause(@NonNull LifecycleOwner owner) { } @Override public void onStop(@NonNull LifecycleOwner owner) { } /** * 释放资源等 * @param owner */ @Override public void onDestroy(@NonNull LifecycleOwner owner) { Log.e(TAG,"onDestroy"); model.endWork(); unregister(); unbindService(); } }
package com.loaderman.architecturecomponents; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { private static String TAG = MainActivity.class.getSimpleName(); private Presenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); presenter = new Presenter(this); //为Lifecycle注册生命周期监听器 getLifecycle().addObserver(presenter); presenter.doWork(); } }
LiveData 是一种持有可被观察数据的类(an observable data holder class)。和其他可被观察的类不同的是,LiveData是有生命周期感知能力的(lifecycle-aware,),这意味着它可以在 activities, fragments, 或者 services 生命周期是活跃状态时更新这些组件。
ViewModel 与 LiveData 之间的关系图如下:
使用:
package com.loaderman.architecturecomponents; public interface BaseViewModel<T> { T loadData(); void clearData(); }
package com.loaderman.architecturecomponents; import android.util.Log; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; public class UserViewModel extends ViewModel implements BaseViewModel<User> { private String TAG = UserViewModel.class.getSimpleName(); private MutableLiveData<User> liveUser; public MutableLiveData<User> getData(){ if(liveUser == null){ liveUser = new MutableLiveData<User>(); } liveUser.setValue(loadData()); return this.liveUser; } public void changeData(){ if(liveUser != null){ liveUser.setValue(loadData()); } } @Override public User loadData() { User user = new User(); user.userId = "00"+(int) ((Math.random() * 10)); user.name = "张三"+(int) ((Math.random() * 10)); user.phone = "12531202310"; Log.i(TAG, "loadData(): " + user.toString()); return user; } @Override public void clearData() { } }
package com.loaderman.architecturecomponents; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private static String TAG = MainActivity.class.getSimpleName(); private Button btn; private TextView tv; UserViewModel mUserViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = findViewById(R.id.tv); btn = findViewById(R.id.btn); // view model.observe mUserViewModel = ViewModelProviders.of(this).get(UserViewModel.class); mUserViewModel.getData().observe(this, new Observer<User>() { @Override public void onChanged(@Nullable User user) { if(user != null){ tv.setText(user.toString()); } } }); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(mUserViewModel != null && mUserViewModel.getData() != null){ mUserViewModel.changeData(); } } }); } }
效果:
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!