Share
Embed
Clean app design with Architecture Components
Handling lifecycle events, maintaining view state, and persisting data are all common challenges on Android that have contributed to the widespread adoption of clean architecture patterns like Model-View-Presenter (MVP) and Model-View-ViewModel (MVVM).
Android Architecture Components is a new collection of libraries announced at Google I/O to help developers manage these same nagging issues. This talk explores how Architecture Components can be leveraged in an app already using clean architecture principles to help make your code even more flexible, maintainable, and testable.
Chuck Greb
November 05, 2017
Transcript
85 slides
-
Clean App Design with Architecture Components .droidconSF 5 Nov 2017
Chuck Greb @ecgreb -
Controller LifecycleActivity Web Service Activity Lifecycle System Services User Input
Dependency Injection Repository Model LiveData Storage Room Presenter ViewModel View EditText EditText Button -
Clean Architecture Build layered applications with clear separation of responsibilities
including view, presentation, and domain logic. Separation of Concerns Synchronize data across screen state, session state, and server state. State Synchronization Enables pure unit tests to test presentation logic and domain models in isolation. Integration and UI tests for components that interact with the framework and/or display. Testability -
“Those who do not remember the past are condemned to
repeat it.” — George Santayana -
Clean Architecture Build layered applications with clear separation of responsibilities
including view, presentation, and domain logic. Separation of Concerns Synchronize data across screen state, session state, and server state. State Synchronization Enables pure unit tests to test presentation logic and domain models in isolation. Integration and UI tests for components that interact with the framework and/or display. Testability -
Clean Architecture Build layered applications with clear separation of responsibilities
including view, presentation, and domain logic. Separation of Concerns Synchronize data across screen state, session state, and server state. State Synchronization Enables pure unit tests to test presentation logic and domain models in isolation. Integration and UI tests for components that interact with the framework and/or display. Testability -
Clean Architecture Build layered applications with clear separation of responsibilities
including view, presentation, and domain logic. Separation of Concerns Synchronize data across screen state, session state, and server state. State Synchronization Enables pure unit tests to test presentation logic and domain models in isolation. Integration and UI tests for components that interact with the framework and/or display. Testability -
Testability • Android framework dependencies encapsulated in view layer •
Pure JVM unit tests for presenters and domain models • Espresso, Robolectric, or UI Automator tests for view layer -
Clean Architecture Build layered applications with clear separation of responsibilities
including view, presentation, and domain logic. Separation of Concerns Synchronize data across screen state, session state, and server state. State Synchronization Enables pure unit tests to test presentation logic and domain models in isolation. Integration and UI tests for components that interact with the framework and/or display. Testability -
GUI Architectures • MVC • MVP • MVVM • MVI
• MVWTF • … -
Supervising Controller (MVC) • Smalltalk-80 • One way flow of
information • Controller handles user input and UI events • View observes changes in domain model State Sync: Data Binding Controller Model onLoginButtonClick() setUser() View View.onClick() -
activity_login.xml <data> <variable name="user" type="com.example.loginator.User"/> </data> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{user.firstName}"/>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{user.lastName}"/> -
Passive View (MVP) • Also called Humble View • No
dependency between view and domain model • Bi-directional flow of information • View replaced by fake in unit tests State Sync: Flow Synchronization Controller onLoginButtonClick View View.onClick() showUser() Presenter onLoginButtonClick() Model getUser() IView showUser() -
class LoginPresenter(private val controller: LoginController) { fun onLoginButtonClick(email: String?, password:
String?) { if (email != null && password != null) { val user = Loginator.getUser(email, password) if (user != null) { controller.showUser(user) } else { controller.showError("Invalid credentials") } } } } LoginPresenter.kt -
Presentation Model (MVVM) • View forwards user input to presentation
model • Presentation model mutates state using domain model • View observes changes in the presentation model State Sync: Observer Pattern ViewModel Model onLoginButtonClick() getUser() View View.onClick() onUpdateUser() updateUser() -
Supervising Controller (MVC) Passive View (MVP) Presentation Model (MVVM) Flow
of Information One way Two way Two way Model <> View Dependency Yes No No Sync Logic View Presenter View State Synchronization Data binding Flow synchronization Observer pattern GUI Architectures -
• Passive view migrates all sync logic into presentation layer
• MVC and MVVM require sync logic in the view layer • For simpler apps, MVC or MVVM may be sufficient • MVP tests are more verbose and require a fake view Humble View is the real MVP -
Android Passive View Controller onLoginButtonClick Presenter Activity Presentation Logic Model
Domain Logic View User Interface Lifecycle Events User Input System Services View -
Android Passive View Controller onLoginButtonClick Presenter Activity Presentation Logic Model
Domain Logic View User Interface Lifecycle Events User Input System Services View -
Android Passive View Controller onLoginButtonClick Presenter Activity Presentation Logic Controller
Model Domain Logic View User Interface Lifecycle Events User Input System Services -
Android Passive View onLoginButtonClick Presenter Activity Presentation Logic Controller Model
Domain Logic View User Interface Lifecycle Events User Input System Services -
Controller onLoginButtonClick Presenter Fake Controller Presentation Logic Controller Model Domain
Logic View User Interface Stub Implementation Presenter Test Model Test Passive View: Unit Tests Test Cases Test Cases -
onLoginButtonClick Presenter Activity Presentation Logic Controller Model Domain Logic View
User Interface Lifecycle Events User Input System Services Passive View: UI Tests Activity Test Test Cases -
class LoginActivity : AppCompatActivity(), LoginController { lateinit var presenter: LoginPresenter
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) presenter = LoginPresenter(this) login_button.setOnClickListener({ presenter.onLoginButtonClick(login_view.email, login_view.password) }) } // ... } LoginActivity.kt -
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <com.example.loginator.LoginView android:id="@+id/login_view" android:layout_width="match_parent" android:layout_height="match_parent"/> <com.example.loginator.UserView
android:id="@+id/user_view" android:layout_width="match_parent" android:layout_height="match_parent"/> </FrameLayout> activity_login.xml -
class LoginView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr:
Int = 0) : LinearLayout(context, attrs, defStyleAttr) { var email: String? = null get() = login_email.text.toString() var password: String? = null get() = login_password.text.toString() var error: String? = null set(value) { login_error.text = value } init { (getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater).inflate(R.layout.view_login, this, true) } } LoginView.kt -
<EditText android:id="@+id/login_email" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <EditText android:id="@+id/login_password" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@+id/login_button"
android:layout_width="wrap_content" android:layout_height=“wrap_content"/> <TextView android:id=“@+id/login_error" android:layout_width="wrap_content" android:layout_height="wrap_content"/> view_login.xml -
class LoginPresenter(private val controller: LoginController) { fun onLoginButtonClick(email: String?, password:
String?) { if (email != null && password != null) { val user = Loginator.getUser(email, password) if (user != null) { controller.showUser(user) } else { controller.showError("Invalid credentials") } } } } LoginPresenter.kt -
class LoginActivity : AppCompatActivity(), LoginController { // ... override fun
showUser(user: User) { login_view.visibility = View.GONE user_view.visibility = View.VISIBLE user_view.user = user } override fun showError(error: String) { login_view.error = error } } LoginActivity.kt -
class UserView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr:
Int = 0) : LinearLayout(context, attrs, defStyleAttr) { var user: User? = null set(value) { user_name.text = value?.name user_email.text = value?.email } init { (getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater).inflate(R.layout.view_user, this, true); } } UserView.kt -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/user_name" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView
android:id="@+id/user_email" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout> view_user.xml -
Android-y challenges • Foreground/background events • Configuration change • Presenter
scope • Long-running operations • Data persistence -
Android Architecture Components • Lifecycle • ViewModel • LiveData •
Room • Paging Library -
Controller LifecycleActivity Web Service Activity Lifecycle System Services User Input
Dependency Injection Repository Model Model Storage Presenter View EditText EditText Button -
class LoginActivity : LifecycleActivity(), LoginController { lateinit var presenter: LoginPresenter
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) presenter = LoginPresenter(this) login_button.setOnClickListener({ presenter.onLoginButtonClick(login_view.email, login_view.password) }) } // ... } LoginActivity.kt -
class LoginActivity : LifecycleActivity(), LoginController { lateinit var presenter: LoginPresenter
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) presenter = LoginPresenter(this) login_button.setOnClickListener({ presenter.onLoginButtonClick(login_view.email, login_view.password) }) } // ... } LoginActivity.kt -
interface LoginController : LifecycleOwner { fun showUser(user: User) fun showError(error:
String) } LoginController.kt -
Controller LifecycleActivity Web Service Activity Lifecycle System Services User Input
Dependency Injection Repository Model Model Storage Presenter View EditText EditText Button -
class LoginViewModel : ViewModel() { var user: User? = null
} LoginViewModel.kt -
class LoginActivity : LifecycleActivity(), LoginController { lateinit var presenter: LoginPresenter
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) val viewModel = ViewModelProviders.of(this).get(LoginViewModel::class.java) presenter = LoginPresenter(this, viewModel) login_button.setOnClickListener({ presenter.onLoginButtonClick(login_view.email, login_view.password) }) } // ... } LoginActivity.kt -
class LoginPresenter(private val controller: LoginController, private val viewModel: LoginViewModel) {
init { viewModel.user.value?.let { controller.showUser(it) } } fun onLoginButtonClick(email: String?, password: String?) { if (email != null && password != null) { val user = Loginator.getUser(email, password) if (user != null) { controller.showUser(user) viewModel.user = user } else { controller.showError("Invalid credentials") } } } } LoginPresenter.kt -
Controller LifecycleActivity Web Service Activity Lifecycle System Services User Input
Dependency Injection Repository Model Model Storage Presenter ViewModel View EditText EditText Button -
class LoginPresenter(private val controller: LoginController, private val viewModel: LoginViewModel) {
init { viewModel.user.observe(controller, Observer<User> { user -> controller.showUser(user) }) } fun onLoginButtonClick(email: String?, password: String?) { if (email != null && password != null) { val user = Loginator.getUser(email, password) if (user != null) { viewModel.user.value = user } else { controller.showError("Invalid credentials") } } } } LoginPresenter.kt -
Controller LifecycleActivity Web Service Activity Lifecycle System Services User Input
Dependency Injection Repository Model LiveData Storage Presenter ViewModel View EditText EditText Button -
@Entity data class User(@PrimaryKey var id: Int, var name: String,
var email: String) User.kt -
@Dao interface UserDao { @Query("SELECT * FROM user WHERE email
LIKE :email LIMIT 1") fun getUserByEmail(email: String): LiveData<User> } UserDao.kt -
@Dao interface UserDao { @Query("SELECT * FROM user WHERE email
LIKE :email LIMIT 1") fun getUserByEmail(email: String): LiveData<User> } UserDao.kt -
class LoginViewModel : ViewModel() { var user: MutableLiveData<User>? = null
fun getUser(email: String, password: String): LiveData<User> { if (user == null) { user = Loginator.getUser(email, password) } return user as LiveData<User> } } LoginViewModel.kt -
class LoginPresenter(private val controller: LoginController, private val viewModel: LoginViewModel) {
init { viewModel.user?.observe(controller, Observer<User> { user -> controller.showUser(user) }) } fun onLoginButtonClick(email: String?, password: String?) { if (email != null && password != null) { val user = viewModel.getUser(email, password) if (user.value == null) { controller.showError("Invalid credentials") } } } } LoginPresenter.kt -
Controller LifecycleActivity Web Service Activity Lifecycle System Services User Input
Dependency Injection Repository Model LiveData Storage Room Presenter ViewModel View EditText EditText Button -
Some thoughts for the future… • Community-driven architecture • Mix
and match components • Fragments? • Lifecycle aware libraries • We are all in this together