Android單項綁定MVVM項目模板

0.前言

事情還要從上週和同事的小聚提及,同事說他們公司如今app的架構模式用的是MVP模式,可是並無經過泛型和繼承等一些列手段強制使用,全靠開發者在Activity或者Fragment裏new一個presenter來作處理,說白了,全靠開發者自覺。這引起了個人一個思考,程序的架構或者設計模式的做用,除了傳統的作到低耦合高內聚,業務分離,我以爲還有一個更重要的一點就是用來約束開發者,雖然使用某種模式或者架構可能並不會節省代碼量,有的甚至會增長編碼工做,可是讓開發者在必定規則內進行開發,保證一個一致性,尤爲是在當一個項目比較大並且須要團隊合做的前提狀況下,就顯得極爲重要。前段時間google公佈了jetpack,旨在幫助開發者更快的構建一款app,以此爲基礎我寫了這個項目模板作了一些封裝,來爲之後本身寫app的時候提供一個支持。java

1.什麼是MVVM

MVVM這種設計模式和MVP極爲類似,只不過Presenter換成了ViewModel,而ViewModel是和View相互綁定的。android

MVPgit

MVVMgithub

我在項目中並無使用這種標準的雙向綁定的MVVM,而是使用了單項綁定的MVVM,經過監聽數據的變化,來更新UI,當UI須要改變是,也是經過改變數據後再來改變UI。具體的App架構參考了google的官方文檔設計模式

2.框架組合

整個模板採用了Retrofit+ViewModel+LiveData的這樣組合,Retrofit用來進行網絡請求,ViewModel用來進行數據存儲於複用,LiveData用來通知UI數據的變化。本篇文章假設您已經熟悉了ViewModel和LiveData。api

3.關鍵代碼分析

3.1Retrofit的處理

首先,網絡請求咱們使用的是Retrofit,Retrofit默認返回的是Call,可是由於咱們但願數據的變化是可觀察和被UI感知的,爲此須要使用LiveData進行對數據的包裹,這裏不對LiveData進行詳細解釋了,只要記住他是一個能夠在Activity或者Fragment生命週期能夠被觀察變化的數據結構便可。你們都知道,Retrofit是經過適配器來決定網絡請求返回的結果是Call仍是什麼別的的,爲此咱們就須要先寫返回結果的適配器,來返回一個LiveData緩存

class LiveDataCallAdapterFactory : CallAdapter.Factory() {

    override fun get(
        returnType: Type,
        annotations: Array<Annotation>,
        retrofit: Retrofit
    ): CallAdapter<*, *>? {
        if (CallAdapter.Factory.getRawType(returnType) != LiveData::class.java) {
            return null
        }
        val observableType = CallAdapter.Factory.getParameterUpperBound(0, returnType as ParameterizedType)
        val rawObservableType = CallAdapter.Factory.getRawType(observableType)
        if (rawObservableType != ApiResponse::class.java) {
            throw IllegalArgumentException("type must be a resource")
        }
        if (observableType !is ParameterizedType) {
            throw IllegalArgumentException("resource must be parameterized")
        }
        val bodyType = CallAdapter.Factory.getParameterUpperBound(0, observableType)
        return LiveDataCallAdapter<Any>(bodyType)
    }
}

class LiveDataCallAdapter<R>(private val responseType: Type) : CallAdapter<R, LiveData<ApiResponse<R>>> {


    override fun responseType() = responseType

    override fun adapt(call: Call<R>): LiveData<ApiResponse<R>> {
        return object : LiveData<ApiResponse<R>>() {
            private var started = AtomicBoolean(false)
            override fun onActive() {
                super.onActive()
                if (started.compareAndSet(false, true)) {
                    call.enqueue(object : Callback<R> {
                        override fun onResponse(call: Call<R>, response: Response<R>) {
                            postValue(ApiResponse.create(response))
                        }

                        override fun onFailure(call: Call<R>, throwable: Throwable) {
                            postValue(ApiResponse.create(throwable))
                        }
                    })
                }
            }
        }
    }
}
複製代碼

首先看LiveDataCallAdapter,這裏在adat方法裏咱們返回了一個LiveData<ApiResponse>,ApiResponse是對返回結果的一層封裝,爲何要封這一層,由於咱們可能會對網絡返回的錯誤或者一些特殊狀況進行特殊處理,這些是能夠再ApiResponse裏作的,而後看LiveDataCallAdapterFactory,返回一個LiveDataCallAdapter,同時強制你的接口定義的網絡請求返回的結果必需是LiveData<ApiResponse>這種結構。使用的時候bash

.object GitHubApi {

    var gitHubService: GitHubService = Retrofit.Builder()
        .baseUrl("https://api.github.com/")
        .addCallAdapterFactory(LiveDataCallAdapterFactory())
        .addConverterFactory(GsonConverterFactory.create())
        .build().create(GitHubService::class.java)


}

interface GitHubService {

    @GET("users/{login}")
    fun getUser(@Path("login") login: String): LiveData<ApiResponse<User>>

}

複製代碼

3.2對ApiResponse的處理

這裏用NetWorkResource對返回的結果進行處理,而且將數據轉換爲Resource幷包入LiveData傳出去。網絡

abstract class NetWorkResource<ResultType, RequestType>(val executor: AppExecutors) {

    private val result = MediatorLiveData<Resource<ResultType>>()

    init {
        result.value = Resource.loading(null)
        val dbData=loadFromDb()
        if (shouldFetch(dbData)) {
            fetchFromNetWork()
        }
        else{
            setValue(Resource.success(dbData))
        }
    }

    private fun setValue(resource: Resource<ResultType>) {

        if (result.value != resource) {
            result.value = resource
        }

    }

    private fun fetchFromNetWork() {
        val networkLiveData = createCall()

        result.addSource(networkLiveData, Observer {

            when (it) {

                is ApiSuccessResponse -> {
                    executor.diskIO().execute {
                        val data = processResponse(it)
                        executor.mainThread().execute {
                            result.value = Resource.success(data)
                        }
                    }
                }

                is ApiEmptyResponse -> {
                    executor.diskIO().execute {
                        executor.mainThread().execute {
                            result.value = Resource.success(null)
                        }
                    }
                }

                is ApiErrorResponse -> {
                    onFetchFailed()
                    result.value = Resource.error(it.errorMessage, null)
                }

            }

        })

    }

    fun asLiveData() = result as LiveData<Resource<ResultType>>

    abstract fun onFetchFailed()

    abstract fun createCall(): LiveData<ApiResponse<RequestType>>

    abstract fun processResponse(response: ApiSuccessResponse<RequestType>): ResultType

    abstract fun shouldFetch(type: ResultType?): Boolean

    abstract fun loadFromDb(): ResultType?

}

複製代碼

這是一個抽象類,關注一下它的幾個抽象方法,這些抽象方法決定了是使用緩存數據仍是去網路請求以及對網絡請求返回結果的處理。其中的AppExecutor是用來處理在主線程更新LiveData,在子線程處理網絡請求結果的。 以後只須要在Repository裏直接返回一個匿名內部類,複寫相應的抽象方法便可。數據結構

class UserRepository {

    private val executor = AppExecutors()

    fun getUser(userId: String): LiveData<Resource<User>> {

        return object : NetWorkResource<User, User>(executor) {
            override fun shouldFetch(type: User?): Boolean {

                return true
            }

            override fun loadFromDb(): User? {
                return null
            }

            override fun onFetchFailed() {

            }

            override fun createCall(): LiveData<ApiResponse<User>> = GitHubApi.gitHubService.getUser(userId)

            override fun processResponse(response: ApiSuccessResponse<User>): User {
                return response.body
            }

        }.asLiveData()
    }

}
複製代碼

3.3對UI的簡單封裝

abstract class VMActivity<T : BaseViewModel> : BaseActivity() {

    protected lateinit var mViewModel: T

    abstract fun loadViewModel(): T

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewModel = loadViewModel()
        lifecycle.addObserver(mViewModel)
    }
}
複製代碼

這裏經過使用集成和泛型,強制開發者在繼承這個類時返回一個ViewMode。 在使用時以下。

class MainActivity : VMActivity<MainViewModel>() {
    override fun loadViewModel(): MainViewModel {
        return MainViewModel()
    }

    override fun getLayoutId(): Int = R.layout.activity_main

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewModel.loginResponseLiveData.observe(this, Observer {

            when (it?.status) {

                Status.SUCCESS -> {
                    contentTV.text = it.data?.reposUrl
                }

                Status.ERROR -> {
                    contentTV.text = "error"
                }

                Status.LOADING -> {
                    contentTV.text = "loading"
                }

            }


        })
        loginBtn.setOnClickListener {
            mViewModel.login("skateboard1991")
        }
    }
}
複製代碼

4.github地址

Github 整個項目就是一個Git的獲取用戶信息的一個簡易demo,還有不少不足,後續在應用過程當中會逐漸完善。

關注個人公衆號

5.參考

github.com/googlesampl…

相關文章
相關標籤/搜索