GitHub地址:Hement:持續更新中html
apk下載地址 react
app詳情 android
歡迎關注個人公衆號 git
LifeCyclegithub
在17年的谷歌IO大會上,Google官方向咱們推出了 Android Architecture Components,其中談到Android組件處理生命週期的問題,向咱們介紹了 Handling Lifecycles。數據庫
因爲和小組成員討論過,感受使用時機尚未到,並且那個時候我反編譯微信的apk,發現也沒有使用的到,因此這個框架的學習計劃就不斷地擱淺,前幾天又反編譯了一下微信的安卓apk,發現它使用了來減小代碼的臃腫! 推薦一個**反編譯工具**api
因此就有必要了解它究竟是個什麼東西bash
爲何要使用Lifecycle微信
咱們在處理Activity或者Fragment組件的生命週期相關時,不可避免會遇到這樣的問題: 咱們在Activity的onCreate()中初始化某些成員(好比MVP架構中的Presenter,或者AudioManager、MediaPlayer等),而後在onStop中對這些成員進行對應處理,在onDestroy中釋放這些資源,這樣致使咱們的代碼也許會像這樣:網絡
class MyPresenter{
public MyPresenter() {
}
void create() {
//do something
}
void destroy() {
//do something
}
}
class MyActivity extends AppCompatActivity {
private MyPresenter presenter;
public void onCreate(...) {
presenter= new MyPresenter ();
presenter.create();
}
public void onDestroy() {
super.onDestroy();
presenter.destory();
}
}
複製代碼
代碼沒有問題,關鍵問題是,實際生產環境中 ,這樣的代碼會很是複雜,你最終會有太多的相似調用而且會致使 onCreate() 和 onDestroy() 方法變的很是臃腫。
如何使用Lifecycle 在前面我寫過一篇文章Hement:MVP架構中的網絡框架(RxJava2+Retrofit2+RxAndroid)(二)這是沒有使用的Lifecycle的網絡請求的Presenter必須在onDestroy時候去銷燬view!
@Override
protected void onDestroy() {
super.onDestroy();
mMainPresenter.detachView();
}
複製代碼
BasePresenter
的中去呢?實際上是能夠滴,只須要把BasePresenter
實現LifecycleObserver
便可public class NewBasePresenter<V extends IMvpView> implements LifecycleObserver {
public static final String TAG = "NewBasePresenter";
private V mMvpView;
public void attachView(V mvpView) {
mMvpView = mvpView;
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
Timber.tag(TAG).d("onDestroy lifecycle event.start ");
detachView();
}
/**
* 因爲在每次這個方法都會去執行,因此能夠這樣進行
* @param owner
* @param event
*/
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
public void onLifecycleChanged(@NotNull LifecycleOwner owner, @NotNull Lifecycle.Event event) {
}
public void detachView() {
mMvpView = null;
}
/**
* 判斷是否還在鏈接在一塊兒的
* @return
*/
public boolean isViewAttached() {
return mMvpView != null;
}
/**
* 獲取View
* @return
*/
public V getMvpView() {
return mMvpView;
}
/**
* 檢查View是否附着
*/
public void checkViewAttached() {
if (!isViewAttached()) throw new MvpViewNotAttachedException();
}
public static class MvpViewNotAttachedException extends RuntimeException {
public MvpViewNotAttachedException() {
super("在綁定數據以前必定要綁定視圖");
}
}
/**
* 這是Observer 中的 onServer ,當咱們調用這個方法,直接就不會走到 onNext中去
* @param disposable
*/
public void dispose(Disposable disposable) {
if (disposable != null && !disposable.isDisposed()) {
disposable.dispose();
}
}
}
複製代碼
public class NewNetWorkPresenter extends NewBasePresenter<NetWorkView> {
private Disposable mDisposable;
private final IRemoteServer mIRemoteServer;
public NewNetWorkPresenter() {
mIRemoteServer = IRemoteServer.Creator.newHementService();
}
@Override
public void attachView(NetWorkView mvpView) {
super.attachView(mvpView);
}
@Override
public void detachView() {
super.detachView();
if (mDisposable != null) mDisposable.dispose();
Timber.tag(TAG).d("onDestroy lifecycle event. end ");
}
public void loadData(String key,String day){
//檢查View是否附着在上面,不在直接拋出異常
checkViewAttached();
//檢查是否往下運行
dispose(mDisposable);
loadData(key,day,new BaseObserver<SMResponse<ArrayList<TodayBean>>>(new SubscriberListener<SMResponse<ArrayList<TodayBean>>>() {
@Override
public void onSubscribe(Disposable disposable) {
super.onSubscribe(disposable);
mDisposable = disposable;
}
@Override
public void onSuccess(SMResponse<ArrayList<TodayBean>> response) {
getMvpView().getDataSuccess(response.result);
}
@Override
public void onFail(String errorCode, String errorMsg) {
getMvpView().getDataFail(errorCode,errorMsg);
}
@Override
public void onError(Throwable e) {
getMvpView().onError(e);
}
}));
}
public void loadData(String key, String day, BaseObserver observer) {
Observable<SMResponse<ArrayList<TodayBean>>> today = mIRemoteServer.getToday(key, day);
today.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(observer);
}
}
複製代碼
private NewNetWorkPresenter mNewNetWorkPresenter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_net_work);
mNewNetWorkPresenter = new NewNetWorkPresenter();
getLifecycle().addObserver(mNewNetWorkPresenter);
}
複製代碼
RxJava2
的依賴,查詢數據的過程在子線程處理數據回調到UI線程,當忽然有一天產品經理說這個頁面的數據咱們要從網絡獲取,那麼你也不肯定那究竟是把代碼刪除了仍是備份,這些你都不知道!因此這時候你就須要獨立綁定getLifecycle().addObserver(mSyncLifecycleObserver);
Activity只關心結果便可!代碼以下api "com.jakewharton.rxrelay2:rxrelay:2.0.0"
複製代碼
public class SyncResponse {
public final SyncResponseEventType eventType;
public final Events comment;
public SyncResponse(SyncResponseEventType eventType, Events comment) {
this.eventType = eventType;
this.comment = comment;
}
}
複製代碼
package com.shiming.hement.lifecycle;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.OnLifecycleEvent;
import android.widget.Toast;
import com.shiming.hement.utils.Events;
import org.w3c.dom.Comment;
import io.reactivex.Completable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;
/**
* <p>
*
* </p>
*
* @author shiming
* @version v1.0
* @since 2018/12/18 10:44
*/
public class SyncLifecycleObserver implements LifecycleObserver {
private static final String TAG = "SyncLifecycleObserver";
private final CompositeDisposable disposables = new CompositeDisposable();
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
Timber.tag(TAG).d("onCreate lifecycle event.");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
Timber.tag(TAG).d("onStart lifecycle event.");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
Timber.tag(TAG).d("onResume lifecycle event.");
disposables.add(SyncRxBus.getInstance().toObservable()
.subscribe(new Consumer<SyncResponse>() {
@Override
public void accept(SyncResponse syncResponse) throws Exception {
handleSyncResponse(syncResponse);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
Timber.tag(TAG).d("onResume lifecycle event. Throwable= %s",throwable);
}
}));
}
private void handleSyncResponse(SyncResponse response) {
if (response.eventType == SyncResponseEventType.SUCCESS) {
onSyncSuccess(response.comment);
} else {
onSyncFailed(response.comment);
}
}
private void onSyncSuccess(Events comment) {
Timber.tag(TAG).d("received sync comment success event for comment %s", comment);
disposables.add(Completable.fromAction(new Action() {
@Override
public void run() throws Exception {
doWhat();
Thread thread = Thread.currentThread();
Timber.tag(TAG).i(thread.toString());
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action() {
@Override
public void run() throws Exception {
Timber.tag(TAG).d(" success");
}
},
new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
Timber.tag(TAG).e(throwable, " error");
}
}));
}
/**
* 能夠作些子線程的數據操做
*/
private void doWhat() {
}
private void onSyncFailed(Events comment) {
Timber.tag(TAG).d("received sync comment failed event for comment %s", comment);
disposables.add(Completable.fromAction(new Action() {
@Override
public void run() throws Exception {
doWhat();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action() {
@Override
public void run() throws Exception {
Timber.tag(TAG).d(" success");
}
},
new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
Timber.tag(TAG).e(throwable, " error");
}
}));
}
/**
* 12-19 15:35:52.317 29721-29721/com.shiming.hement D/SyncLifecycleObserver: received sync comment success event for comment Events=我是NewRxBusDemoActivity中發出成功的事件
* 12-19 15:35:52.318 29721-29834/com.shiming.hement I/SyncLifecycleObserver: Thread[RxCachedThreadScheduler-2,5,main]
* 12-19 15:35:52.318 29721-29721/com.shiming.hement D/SyncLifecycleObserver: received sync comment success event for comment Events=我是NewRxBusDemoActivity中發出成功的事件
* 12-19 15:35:52.319 29721-29835/com.shiming.hement I/SyncLifecycleObserver: Thread[RxCachedThreadScheduler-3,5,main]
* 12-19 15:35:52.320 29721-29721/com.shiming.hement D/SyncLifecycleObserver: received sync comment success event for comment Events=我是NewRxBusDemoActivity中發出成功的事件
* 12-19 15:35:52.321 29721-29834/com.shiming.hement I/SyncLifecycleObserver: Thread[RxCachedThreadScheduler-2,5,main]
* 12-19 15:35:52.323 29721-29721/com.shiming.hement D/SyncLifecycleObserver: success
* 12-19 15:35:52.330 29721-29721/com.shiming.hement D/SyncLifecycleObserver: success
*/
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
Timber.tag(TAG).d("onPause lifecycle event.");
// 若是不在這裏
disposables.clear();
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
Timber.tag(TAG).d("onStop lifecycle event.");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
Timber.tag(TAG).d("onDestroy lifecycle event.");
}
/**
* 全部的事件都會輸出
*/
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
public void onAny() {
Timber.tag(TAG).d("onAny 全部的事件都會輸出");
}
}
複製代碼
public enum SyncResponseEventType {
SUCCESS,
FAILED
}
複製代碼
public class SyncRxBus {
private static SyncRxBus instance;
private final PublishRelay<SyncResponse> relay;
public static synchronized SyncRxBus getInstance() {
if (instance == null) {
instance = new SyncRxBus();
}
return instance;
}
private SyncRxBus() {
relay = PublishRelay.create();
}
public void post(SyncResponseEventType eventType, Events comment) {
relay.accept(new SyncResponse(eventType, comment));
}
public Observable<SyncResponse> toObservable() {
return relay;
}
}
複製代碼
// 若是使用的多的話,能夠放在BaseActivity中
private SyncLifecycleObserver mSyncLifecycleObserver = new SyncLifecycleObserver();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rx_bus_layout);
getLifecycle().addObserver(mSyncLifecycleObserver);
findViewById(R.id.btn_mock_send_s_onclick).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Events events = new Events("我是NewRxBusDemoActivity中發出成功的事件");
SyncRxBus.getInstance().post(SyncResponseEventType.SUCCESS, events);
}
});
findViewById(R.id.btn_mock_send_f_onclick).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Events events = new Events("我是NewRxBusDemoActivity中發出失敗的事件");
SyncRxBus.getInstance().post(SyncResponseEventType.FAILED, events);
}
});
複製代碼
若是後續咱們不須要使用的話,直接就把Activity中兩行代碼註釋掉就行~~~
GitHub地址:Hement:持續更新中
感謝如下博客對個人幫助