簡體   English   中英

在Android MVP中,演示者應該返回一個值嗎?

[英]In Android MVP, should a presenter return a value?

我試着學習MVP,我有一些問題要問,演示者是否應該返回一個值?

這樣的事情:

class MainPresenter : BasePresenter<MainContract.View>(), MainContract.Actions {
    override fun getProducts (id: Int): List<Product> {
        //...
        return products
    }
}

interface MainContract {
    interface Actions {
        fun getProducts(id: Int): List<Product>
    }
}

或者像這樣:

class MainPresenter : BasePresenter<MainContract.View>(), MainContract.Actions {
    override fun getProducts (id: Int) {
        //...
        mvpView?.showProducts(products)
    }
}

interface MainContract {
    interface Actions {
        fun getProducts(id: Int)
    }

    interface View{
        fun showProducts(products: List<Product>)
    }
}

我們要問的第一個問題是,主持人應該向誰返回價值? 誰對演示者的價值感興趣? 我們想用視圖層搞亂我們的業務邏輯嗎? 鑒於我們的業務邏輯在演示者本身內部,還有誰對任何數據感興趣?

絕對不是我們的意圖,而是偏離MVP。 我們需要通過接口傳播值,通常是View層方法,並將它們作為參數傳遞給駐留在視圖層中的其他感興趣的各方。

TL; DR:選項#2

這是一個自以為是的答案,但我通常會嘗試向演示者注入某種抽象view引用。 基本上是一個接口,其中實際的實現可以是活動,片段或視圖,但對於演示者而言,這並不重要。 所有它知道的,是界面提出的合同。

我傾向於不會從演示者那里返回值。 我會向獲取產品的演示者注入另一個抽象。 我們通常稱他們為互動者。 它的職責是從后台線程上的存儲庫中獲取並在main上傳遞結果。 回調的經典方式看起來像這樣(但你應該考慮使用kotlin協程,這樣可以避免回調):

class MainPresenter(val interactor: MainInteractor) : BasePresenter<MainContract.View>(), MainContract.Actions, MainContract.Interactor.Callback {
    override fun getProduct (id: Int) {
        //...
        interactor.getProduct(product, this) // this is the callback
    }

    override fun onResult(result: Product) {
        mvpView?.showProduct(result)
    }
}

interface MainContract {
    interface Interactor {
        interface Callback<T> { fun onResult(result: T) }
        fun getProduct(id: Int, listener: Callback<Product>)
    }

    interface View{
        fun showProduct(product: Product)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM