CapybaraArch是Capybara系列里的一個Android架構妻枕,包含MVVM基礎組件、網絡請求粘驰、校驗器(編寫文檔中)、埋點(開發(fā)中)愕掏。
按照慣例,先放上Github
-
Github https://github.com/Ubitar/Capybara-Arch
————————————————————————————————————————————————————————
1亭珍、MVVM基礎組件
基于Databinding的MVVM庫
- Model、View肄梨、ViewModel職責明確,可通過實現(xiàn)其接口實現(xiàn)更多組件
- 整合 fragmentation 改(僅適配setMaxLifecycle众羡,不兼容setUserVisibleHint()的情況)
- 提供簡易 Controller 實現(xiàn)(控制顯示加載框/顯示提示消息/顯示加載成功)
2、網絡請求
基于Retrofit的網絡請求庫
- 使用經典Retrofit+Rxjava組合
- 支持自定義Okhttp粱侣、自定義解析和錯誤統(tǒng)一處理
1、導入
repositories {
jcenter()
}
MVVM庫 :
implementation 'com.ubitar.capybara:archcapybara-mvvm:1.2.0'
//以下為其他必要的依賴
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
網絡庫:
implementation 'com.ubitar.capybara:archcapybara-network:1.2.0'
//以下為其他必要的依賴 可自定義版本
implementation 'io.reactivex.rxjava2:rxjava:2.2.8'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.google.code.gson:gson:2.8.6'
2油猫、MVVM基礎組件
不熟悉MVVM或想進一步了解的同學可以先看看這篇文章和精簡demo
Capybara-MVVM 一個Android基礎組件架構柠偶,面還是我在吹牛逼
(1) 架構與Fragmentation耦合使用,且對Fragmentation做出了修改诱担,僅兼容SDK29 后更新的setMaxLifecycle控制生命周期毡证,不兼容使用setUserVisibleHint控制生命周期,例如ViewPager1
蔫仙。
拓展:Fragmentation如何兼容新版本的setMaxLifecycle
(2)框架中在 View和ViewModel 之間嵌入了Controller的機制料睛,方便
3摇邦、網絡請求
網絡請求使用Retrofit封裝,支持多個Host及添加攔截器涎嚼,支持自定網絡請求返回處理。
在Application中新增請求的Host苔货,及其網絡攔截器。
NetworkManager.getInstance().addServer(
NetworkTag.DEFAULT_HOST_TAG, Server.create(Host.DEFAULT_HOST_URL, {
// 此處可以添加Logger攔截器或修改響應時間
// it.addInterceptor(LoggerInterceptor())
// it.addInterceptor(TokenInterceptor())
}))
編寫Retrofit接口服務文件
interface Demo4Api {
@FormUrlEncoded
@POST("student/login")
fun login(
@Field("account") account: String,
@Field("password") password: String
): Flowable<UserBean>
}
class DemoRepository : BaseRepository<Demo4Api>() {
//確認接口路徑文件
override fun getApi(): Class<Demo4Api> {
return Demo4Api::class.java
}
//設置服務標識夜惭,用以綁定Host
override fun getServerTag(): String {
return NetworkTag.DEFAULT_HOST_TAG
}
//網絡請求中間預處理層铛绰,用于加密或轉Map等輕處理
fun login(account: String, password: String): Flowable<UserBean> {
return repository.login(account, password)
}
}
在model層請求網絡
class DemoModel(
private val viewModel: Demo4ViewModel
) : BaseModel(viewModel) {
private val demoRepository = DemoRepository()
fun toLogin(account: String, password: String) {
demoRepository.login(account, password)
.compose(SchedulerCompose.io2main())
.compose()/轉換數(shù)據(jù)數(shù)據(jù)
.retryWhen(RetryWhenFunction(3000, 3))//網絡問題重試請求
.subscribe({
//得到數(shù)據(jù)后做處理
})
}
(未完,后續(xù)會補全優(yōu)化文檔)