擁有生命周期的Presenter的MVP框架,支持Multi P

結(jié)合自己對MVP的理解领突,加上個人習(xí)慣险耀,整理出這么一份Android MVP框架

  • 通過注解動態(tài)注入Presenter
  • Presenter擁有完整生命周期
  • 支持多Presenter注入
  • 狀態(tài)復(fù)原

0x00 前言

此框架可以說是Fork nucleus 而來,只不過結(jié)合了個人理解和習(xí)慣進(jìn)行更改则拷,放上此框架鏈接
https://github.com/izyhang/Damon/tree/feature/multi-presenter

0x01 介紹

先介紹一下Damon的簡單使用

新建View贡蓖、Presenter

Presenter具有與Activity一樣的生命周期,這里展示部分生命周期

interface MainView {
    fun log(msg: String)
}

class MainPresenter : BasePresenter<MainView>() {
    override fun onCreate(arguments: Bundle?, savedState: Bundle?) {
        super.onCreate(arguments, savedState)
        view.log("MainPresenter.onCreate")
    }

    override fun onResume() {
        super.onResume()
        view.log("MainPresenter.onResume")
    }

    override fun onPause() {
        super.onPause()
        view.log("MainPresenter.onPause")
    }

    override fun onDestroy() {
        super.onDestroy()
        view.log("MainPresenter.onDestroy")
    }
}

修改MainActivity

MainActivity綁定Presenter煌茬,想要拿到Presenter通過@BindPresenter獲取

@RequiresPresenter(MainPresenter::class)
class MainActivity : BaseActivity(), MainView {
    @BindPresenter
    private var mainPresenter: MainPresenter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mainPresenter.xxx()
    }

    override fun log(msg: String) {
        println(msg)
    }
}

多Presenter注入

@RequiresPresenter(value = [MainPresenter::class, SecondPresenter::class])
class MainActivity : BaseActivity(), MainView, SecondView {
    @BindPresenter
    private var mainPresenter: MainPresenter? = null
    @BindPresenter
    private var secondPresenter: SecondPresenter? = null

    override fun log(msg: String) {
        println(msg)
    }
}

0x02 工作原理

下面介紹一下Damon的工作原理

Presenter的動態(tài)注入和賦值

用注解代替手動實(shí)例化Presenter更加方便斥铺,并且在封裝好的Activity實(shí)現(xiàn)了狀態(tài)恢復(fù),避免重復(fù)創(chuàng)建Presenter

在界面創(chuàng)建之時會傳入當(dāng)前classReflectionPresenterFactory坛善,通過cls.getAnnotation拿到@RequiresPresenter注解并保存晾蜘,在這里也對當(dāng)前class@BindPresenter注解的成員進(jìn)行保存

@Nullable
public static ReflectionPresenterFactory fromViewClass(Object host, Class<?> cls) {
    RequiresPresenter annotation = cls.getAnnotation(RequiresPresenter.class);
    Class<? extends MvpPresenter>[] pClass = null != annotation ? annotation.value() : null;
    if (null == pClass) {
        return null;
    }
    List<Field> fields = new ArrayList<>();
    for (Field field : cls.getDeclaredFields()) {
        Annotation[] annotations = field.getDeclaredAnnotations();
        if (annotations.length < 1) {
            continue;
        }
        if (annotations[0] instanceof BindPresenter) {
            fields.add(field);
        }
    }
    return new ReflectionPresenterFactory(host, pClass, fields);
}

Presenter的創(chuàng)建

上面講過DamonPresenter是具有完整生命周期的,看到封裝的Activity MvpAppCompatActivity.java

Activity的生命周期通過PresenterLifecycleDelegate去控制Presenter的方法調(diào)用眠屎,賦予其生命周期剔交。其中還重載了onSaveInstanceState輔助Presenter狀態(tài)恢復(fù)機(jī)制

public class MvpAppCompatActivity extends AppCompatActivity implements MvpView {

    private static final String PRESENTER_STATE_KEY = "presenter_state";
    private PresenterLifecycleDelegate mPresenterDelegate =
            new PresenterLifecycleDelegate(ReflectionPresenterFactory.fromViewClass(this, getClass()));

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenterDelegate.onCreate(this, getIntent().getExtras(), null != savedInstanceState ? savedInstanceState.getBundle(PRESENTER_STATE_KEY) : null);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBundle(PRESENTER_STATE_KEY, mPresenterDelegate.onSaveInstanceState());
    }

    @Override
    public void onStart() {
        super.onStart();
        mPresenterDelegate.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenterDelegate.onResume();
    }

    @Override
    public void onPause() {
        mPresenterDelegate.onPause();
        super.onPause();
    }

    @Override
    public void onStop() {
        mPresenterDelegate.onStop();
        super.onStop();
    }

    @Override
    public void onDestroy() {
        mPresenterDelegate.onDestroy(!isChangingConfigurations());
        super.onDestroy();
    }
}

PresenterLifecycleDelegate

最重要的就是此類,連接ActivityPresenter的樞紐改衩,控制Presenter的創(chuàng)建岖常、恢復(fù)、生命周期

public class PresenterLifecycleDelegate {

    private static final String PRESENTER_KEY = "presenter - ";
    private static final String PRESENTER_ID_KEYS = "presenter_ids";

    @Nullable
    private PresenterFactory mPresenterFactory;
    @Nullable
    private List<? extends MvpPresenter> mPresenters;

    private boolean mPresenterHasView;

    public PresenterLifecycleDelegate(@Nullable PresenterFactory presenterFactory) {
        this.mPresenterFactory = presenterFactory;
    }

    public void onCreate(MvpView view, @Nullable Bundle arguments, @Nullable Bundle savedState) {
        if (mPresenterFactory == null) {
            return;
        }
        Bundle presenterBundle = null;
        if (savedState != null) {
            presenterBundle = ParcelFn.unmarshall(ParcelFn.marshall(savedState));
        }
        createPresenter(presenterBundle);
        if (mPresenters != null && !mPresenters.isEmpty()) {
            mPresenterFactory.bindPresenter(mPresenters);
            for (MvpPresenter presenter : mPresenters) {
                //noinspection unchecked
                presenter.create(view, arguments, null != presenterBundle ? presenterBundle.getBundle(PRESENTER_KEY.concat(presenter.getClass().getSimpleName())) : null);
            }
        }
    }

    private void createPresenter(Bundle presenterBundle) {
        if (presenterBundle != null) {
            mPresenters = PresenterStorage.INSTANCE.getPresenter(presenterBundle.getStringArray(PRESENTER_ID_KEYS));
        }

        if (mPresenters == null) {
            //noinspection ConstantConditions
            mPresenters = mPresenterFactory.createPresenter();
            PresenterStorage.INSTANCE.add(mPresenters);
        }
    }

    public void onStart() {
        if (mPresenters != null && !mPresenters.isEmpty()) {
            for (MvpPresenter presenter : mPresenters) {
                presenter.start();
            }
        }
    }

    public Bundle onSaveInstanceState() {
        Bundle bundle = new Bundle();
        if (mPresenters != null && !mPresenters.isEmpty()) {
            String[] ids = new String[mPresenters.size()];
            for (MvpPresenter presenter : mPresenters) {
                Bundle presenterBundle = new Bundle();
                presenter.save(presenterBundle);
                bundle.putBundle(PRESENTER_KEY.concat(presenter.getClass().getSimpleName()), presenterBundle);

                ids[mPresenters.indexOf(presenter)] = PresenterStorage.INSTANCE.getId(presenter);
            }
            bundle.putStringArray(PRESENTER_ID_KEYS, ids);
        }
        return bundle;
    }

    public void onResume() {
        if (mPresenters != null && !mPresenters.isEmpty() && !mPresenterHasView) {
            for (MvpPresenter presenter : mPresenters) {
                presenter.resume();
            }
            mPresenterHasView = true;
        }
    }

    public void onPause() {
        if (mPresenters != null && !mPresenters.isEmpty() && mPresenterHasView) {
            for (MvpPresenter presenter : mPresenters) {
                presenter.pause();
            }
            mPresenterHasView = false;
        }
    }

    public void onStop() {
        if (mPresenters != null && !mPresenters.isEmpty()) {
            for (MvpPresenter presenter : mPresenters) {
                presenter.stop();
            }
        }
    }

    public void onDestroy(boolean isFinal) {
        if (isFinal && mPresenters != null && !mPresenters.isEmpty()) {
            for (MvpPresenter presenter : mPresenters) {
                presenter.destroy();
            }
            mPresenters.clear();
            mPresenters = null;
        }
    }
}

0x03 講在最后

該框架實(shí)現(xiàn)的Presenter恢復(fù)機(jī)制葫督,存儲的id不止是單純的Presenter類名竭鞍,大可不必?fù)?dān)心Presenter復(fù)用混亂的情況,具體可以看 PresenterStorage.java 的實(shí)現(xiàn)

此次說講Multi Presenter版本的Damon是新變支的2.0.0-alpha候衍,未經(jīng)過大量測試笼蛛。
不過此前的Single Presenter版本的Damon洒放,版本號1.1.0蛉鹿,則在開發(fā)環(huán)境穩(wěn)定運(yùn)行許久

最后再放上項(xiàng)目鏈接https://github.com/izyhang/Damon/tree/feature/multi-presenter

歡迎大家指出不足、留下您的意見~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末往湿,一起剝皮案震驚了整個濱河市妖异,隨后出現(xiàn)的幾起案子惋戏,更是在濱河造成了極大的恐慌,老刑警劉巖他膳,帶你破解...
    沈念sama閱讀 210,914評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件响逢,死亡現(xiàn)場離奇詭異,居然都是意外死亡棕孙,警方通過查閱死者的電腦和手機(jī)舔亭,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,935評論 2 383
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蟀俊,“玉大人钦铺,你說我怎么就攤上這事≈ぃ” “怎么了矛洞?”我有些...
    開封第一講書人閱讀 156,531評論 0 345
  • 文/不壞的土叔 我叫張陵,是天一觀的道長烫映。 經(jīng)常有香客問我沼本,道長,這世上最難降的妖魔是什么锭沟? 我笑而不...
    開封第一講書人閱讀 56,309評論 1 282
  • 正文 為了忘掉前任抽兆,我火速辦了婚禮,結(jié)果婚禮上族淮,老公的妹妹穿的比我還像新娘郊丛。我一直安慰自己,他們只是感情好瞧筛,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,381評論 5 384
  • 文/花漫 我一把揭開白布厉熟。 她就那樣靜靜地躺著,像睡著了一般较幌。 火紅的嫁衣襯著肌膚如雪揍瑟。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,730評論 1 289
  • 那天乍炉,我揣著相機(jī)與錄音绢片,去河邊找鬼。 笑死岛琼,一個胖子當(dāng)著我的面吹牛底循,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播槐瑞,決...
    沈念sama閱讀 38,882評論 3 404
  • 文/蒼蘭香墨 我猛地睜開眼熙涤,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起祠挫,我...
    開封第一講書人閱讀 37,643評論 0 266
  • 序言:老撾萬榮一對情侶失蹤那槽,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后等舔,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體骚灸,經(jīng)...
    沈念sama閱讀 44,095評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,448評論 2 325
  • 正文 我和宋清朗相戀三年慌植,在試婚紗的時候發(fā)現(xiàn)自己被綠了甚牲。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,566評論 1 339
  • 序言:一個原本活蹦亂跳的男人離奇死亡蝶柿,死狀恐怖鳖藕,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情只锭,我是刑警寧澤著恩,帶...
    沈念sama閱讀 34,253評論 4 328
  • 正文 年R本政府宣布,位于F島的核電站蜻展,受9級特大地震影響喉誊,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜纵顾,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,829評論 3 312
  • 文/蒙蒙 一伍茄、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧施逾,春花似錦敷矫、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,715評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至蠕搜,卻和暖如春怎茫,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背妓灌。 一陣腳步聲響...
    開封第一講書人閱讀 31,945評論 1 264
  • 我被黑心中介騙來泰國打工轨蛤, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人虫埂。 一個月前我還...
    沈念sama閱讀 46,248評論 2 360
  • 正文 我出身青樓祥山,卻偏偏與公主長得像,于是被迫代替她去往敵國和親掉伏。 傳聞我的和親對象是個殘疾皇子缝呕,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,440評論 2 348

推薦閱讀更多精彩內(nèi)容