Android Architecture — MVVM

Dave Chao
5 min readJan 9, 2020

--

去年開發了一款Android App,專案架構上導入了Android Jetpack、Koin以及Coroutines。在開發過程中充滿挑戰,因為要在最短的時程內將這些技術整合,需要不斷思考與調整,才能完成的。

本篇主要介紹 MVVM + Koin + Coroutines 的架構設計

在專案架構上,直接使用了Android官方的MVVM架構去實作,並且導入了Android Jetpack Components,分別是Navigation、LiveData以及Paging。另外針對API的部分,導入了OkHttp和Retrofit,並且搭配Coroutines使用。

MVVM

  • Activity 和 Fragment 進行UI操作,告訴ViewModel要做什麼事情,並且使用LiveData觀察資料,依據資料變動,更新UI。
  • ViewModel主要處理Business Logic
  • Repository主要提供資料給ViewModel

Dependency Injection

在程式開發的過程中,常常遇到物件之間相依性太高的問題,因此會透過DI機制解決問題。針對DI,Android目前提供兩種套件,分別是 Dagger 和 Koin:

Dagger:

  • Pure Java
  • Stable、Flexible、Powerful
  • No runtime error
  • Fast in runtime
  • Compile time overhead
  • Hard to learn

Koin:

  • Pure Kotlin
  • No code generation
  • No annotation processing
  • No compile time overhead
  • Easy to learn and setup
  • Error in runtime

基於以上分析,專案決定導入Koin,接下來我會說明如何導入:

自訂Module以及物件之間的相依性

將自訂的Module加入到Koin中,並且啟用它。

  • Koin支援注入ViewModel,因此只需使用 by viewModel 的方式注入

private val viewModel by viewModel<PersonalViewModel>()

  • 若要在其他地方注入物件,首先必須先繼承 KoinComponent,然後只需使用 by inject 的方式注入。

private val apiRepository: ApiRepository by inject()

Concurrency

在Android中遇到Concurrency問題時,目前有三種解決方案,分別如下:

RxJava非常強大,但是RxJava也帶來了許多問題,如下:

  • 學習曲線太高
  • Operator過多
  • Thread切換的問題
  • Rx-chain debug難度高
  • 使用了RxJava設計的Module,導致其他地方也需要使用RxJava。

現在Kotlin提供了Coroutines後,讓Android不再只有RxJava的選擇,Coroutines完全可以替代RxJava。Coroutines的優勢如下:

  • 學習門檻低
  • 提供Flow機制,讓Android擁有了RxJava Operator的功能。
  • 去除callback機制,讓非同步程式撰寫起來像同步程式一樣的自然。

另外,Coroutines針對Thread管控有三種,如下:

  • Dispatcher.Main:用於操作UI
  • Dispatcher.IO:用在 IO 耗時作業,例如:Network、Disk
  • Dispatcher.Default:用於CPU運算

接下來會以抓取Github User Detail為例

針對API部分,自訂API接口以及自訂API回傳結果的通用型態 Sealed Class

針對ViewModel部分,透過 viewModelScope.launch 啟動一個Coroutines,並且運用 Flow 的機制,將呼叫API的整個過程串在一起,最後再透過 emit 的機制觸發 collect,將資料結果傳給LiveData。

針對View部分,觸發ViewModel定義的Business Logic,同時觀察ViewModel定義的LiveData,若LiveData發生變化,則更新UI。

以上是我實作Android MVVM架構的歷程,MVVM將UI、Business Logic和Data劃分開來。透過Koin的DI機制,讓物件之間保持高內聚、低耦合。此外運用了Coroutines、Flow以及Sealed Class,讓異步處理變得簡單明瞭,專案程式變得非常乾淨且好維護。

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Dave Chao
Dave Chao

No responses yet

Write a response