MVVM模式封裝實踐

MVVM模式基於數據驅動UI,咱們能夠經過ViewModel很好的解藕ActivityView。相對於MVP模式PresenterView交互頻繁,工程結構複雜,MVVM模式更加清晰簡潔。有了DataBindingView層功能再也不變得很弱,經過綁定屬性/事件,能夠佈局文件中完成ViewModelView的交互。下面以Wandroid項目中的文章搜索功能來看看我對於MVVM模式的封裝實踐,也歡迎評論談談你們的見解。php

項目地址

github.com/iamyours/Wa…java

DataBinding自定義屬性與事件

新建一個CommonBindings.kt文件,用於處理DataBinding自定義屬性/事件,這裏添加搜索業務要用到的SmartRefreshLayoutEditTextBindingAdapter,代碼以下android

@BindingAdapter( value = ["refreshing", "moreLoading", "hasMore"], requireAll = false )
fun bindSmartRefreshLayout( smartLayout: SmartRefreshLayout, refreshing: Boolean, moreLoading: Boolean, hasMore: Boolean ) {//狀態綁定,控制中止刷新
    if (!refreshing) smartLayout.finishRefresh()
    if (!moreLoading) smartLayout.finishLoadMore()
    smartLayout.setEnableLoadMore(hasMore)
}

@BindingAdapter( value = ["autoRefresh"] )
fun bindSmartRefreshLayout( smartLayout: SmartRefreshLayout, autoRefresh: Boolean ) {//控制自動刷新
    if (autoRefresh) smartLayout.autoRefresh()
}

@BindingAdapter(//下拉刷新,加載更多 value = ["onRefreshListener", "onLoadMoreListener"], requireAll = false )
fun bindListener( smartLayout: SmartRefreshLayout, refreshListener: OnRefreshListener?, loadMoreListener: OnLoadMoreListener? ) {
    smartLayout.setOnRefreshListener(refreshListener)
    smartLayout.setOnLoadMoreListener(loadMoreListener)
}

//綁定軟鍵盤搜索
@BindingAdapter(value = ["searchAction"])
fun bindSearch(et: EditText, callback: () -> Unit) {
    et.setOnEditorActionListener { v, actionId, event ->
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            callback()
            et.hideKeyboard()
        }
        true
    }
}
複製代碼

BaseViewModel

咱們將經常使用到的的屬性和方法加入到BaseViewModel中,搜索具備分頁功能,所以須要refreshingmoreLoading控制結束下拉刷新,加載更多,autoRefresh來控制SmartRefreshLayout自動刷新,hasMore控制是否還有更多,page控制分頁請求,在mapPage方法中贊成處理分頁數據(刷新狀態,是否更多)git

open class BaseViewModel : ViewModel() {
    protected val api = WanApi.get()

    protected val page = MutableLiveData<Int>()
    val refreshing = MutableLiveData<Boolean>()
    val moreLoading = MutableLiveData<Boolean>()
    val hasMore = MutableLiveData<Boolean>()
    val autoRefresh = MutableLiveData<Boolean>()//SmartRefreshLayout自動刷新標記

    fun loadMore() {
        page.value = (page.value ?: 0) + 1
        moreLoading.value = true
    }

    fun autoRefresh() {
        autoRefresh.value = true
    }

    open fun refresh() {//有些接口第一頁可能爲1,因此要重寫
        page.value = 0
        refreshing.value = true
    }

    /** * 處理分頁數據 */
    fun <T> mapPage(source: LiveData<ApiResponse<PageVO<T>>>): LiveData<PageVO<T>> {
        return Transformations.map(source) {
            refreshing.value = false
            moreLoading.value = false
            hasMore.value = !(it?.data?.over ?: false)
            it.data
        }
    }

}
複製代碼

SearchVM

而後建立SearchVM做爲搜索業務的ViewModelgithub

class SearchVM : BaseViewModel() {
    val keyword = MutableLiveData<String>()

    //類型爲LiveData<ApiResponse<PageVO<ArticleVO>>>
    private val _articlePage = Transformations.switchMap(page) {
        api.searchArticlePage(it, keyword.value ?: "")
    }
    //類型LiveData<PageVO<ArticleVO>>
    val articlePage = mapPage(_articlePage)

    fun search() {//搜索數據
        autoRefresh()
    }
}
複製代碼

佈局文件

以前已經添加了DataBinding的自定義屬性/事件,咱們如今在佈局中使用它。 先添加SearchVM用於數據交互api

<variable name="vm" type="io.github.iamyours.wandroid.ui.search.SearchVM"/>

複製代碼

而後在SmartRefreshLayout中綁定事件和屬性bash

<com.scwang.smartrefresh.layout.SmartRefreshLayout ... app:onRefreshListener="@{()->vm.refresh()}" app:refreshing="@{vm.refreshing}" app:moreLoading="@{vm.moreLoading}" app:hasMore="@{vm.hasMore}" app:autoRefresh="@{vm.autoRefresh}" app:onLoadMoreListener="@{()->vm.loadMore()}">


複製代碼

EditText中雙向綁定keyword屬性,添加軟鍵盤搜索事件app

<EditText ... android:text="@={vm.keyword}" android:imeOptions="actionSearch" app:searchAction="@{()->vm.search()}" />
複製代碼

完整佈局以下:ide

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable name="vm" type="io.github.iamyours.wandroid.ui.search.SearchVM"/>
    </data>

    <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">

        <RelativeLayout android:layout_width="match_parent" android:layout_height="48dp">

            <TextView android:id="@+id/tv_cancel" android:layout_width="wrap_content" android:layout_height="match_parent" android:textSize="14sp" android:layout_marginRight="10dp" android:gravity="center" android:textColor="@color/text_color" android:layout_alignParentRight="true" android:text="取消" app:back="@{true}" />

            <EditText android:layout_width="match_parent" android:layout_height="40dp" android:layout_toLeftOf="@id/tv_cancel" android:lines="1" android:layout_marginRight="10dp" android:inputType="text" android:paddingLeft="40dp" android:hint="搜索關鍵詞以空格隔開" android:layout_centerVertical="true" android:textSize="14sp" android:layout_marginLeft="10dp" android:textColor="@color/title_color" android:textColorHint="@color/text_color" android:background="@drawable/bg_search" android:text="@={vm.keyword}" android:imeOptions="actionSearch" app:searchAction="@{()->vm.search()}" />

            <ImageView android:id="@+id/iv_search" android:layout_width="48dp" android:layout_height="48dp" android:tint="@color/text_color" android:src="@drawable/ic_search" android:padding="13dp" android:layout_marginLeft="10dp" />
        </RelativeLayout>

        <View android:layout_width="match_parent" android:layout_height="1px" android:background="@color/divider" />

        <com.scwang.smartrefresh.layout.SmartRefreshLayout android:id="@+id/refreshLayout" android:layout_width="match_parent" app:onRefreshListener="@{()->vm.refresh()}" app:refreshing="@{vm.refreshing}" app:moreLoading="@{vm.moreLoading}" app:hasMore="@{vm.hasMore}" app:autoRefresh="@{vm.autoRefresh}" android:background="@color/bg_dark" app:onLoadMoreListener="@{()->vm.loadMore()}" android:layout_height="match_parent">

            <com.scwang.smartrefresh.layout.header.ClassicsHeader android:layout_width="match_parent" app:srlAccentColor="@color/text_color" app:srlPrimaryColor="@color/bg_dark" android:layout_height="wrap_content"/>

            <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:overScrollMode="never" tools:listitem="@layout/item_qa" android:layout_width="match_parent" android:layout_height="match_parent"/>

            <com.scwang.smartrefresh.layout.footer.ClassicsFooter android:layout_width="match_parent" app:srlAccentColor="@color/text_color" app:srlPrimaryColor="@color/bg_dark" android:layout_height="wrap_content"/>
        </com.scwang.smartrefresh.layout.SmartRefreshLayout>
    </LinearLayout>
</layout>
複製代碼

Activity中監聽數據,更新ui

爲了簡化ViewModel的建立,新建FragmentActivity的擴展函數,見Lazy.kt,每次以lazy形式初始化。函數

inline fun <reified T : ViewModel> FragmentActivity.viewModel() =
    lazy { ViewModelProviders.of(this).get(T::class.java) }
複製代碼

建立BaseActivity

open abstract class BaseActivity<T : ViewDataBinding> : AppCompatActivity() {
    abstract val layoutId: Int
    lateinit var binding: T

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, layoutId)
        binding.lifecycleOwner = this
    }
}
複製代碼

而後新建SearchActivity,完成最後一步

class SearchActivity : BaseActivity<ActivitySearchBinding>() {
    override val layoutId: Int
        get() = R.layout.activity_search
    val vm by viewModel<SearchVM>()
    val adapter = ArticleAdapter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.vm = vm
        initRecyclerView()
    }

    private fun initRecyclerView() {
        binding.recyclerView.also {
            it.adapter = adapter
            it.layoutManager = LinearLayoutManager(this)
        }
        vm.articlePage.observe(this, Observer {
            adapter.addAll(it.datas, it.curPage == 1)
        })
    }
}
複製代碼

關於Adapter的封裝見這裏DataBoundAdapter

搜索最終效果

經過SearchActivitySearchVM,能夠看到activity和view徹底解耦,咱們將業務邏輯放到ViewModel中,經過修改LiveData觸發ui的變化。

搜索文章
相關文章
相關標籤/搜索