Android Architecture Components


Source link: https://github.com/KucherenkoIhor/Android-Architecture-Components

Android Architecture Components

Read article here

Android Architecture Components (AAC) is a new collection of libraries that contains the lifecycle-aware components. It can solve problems with configuration changes, supports data persistence, reduces boilerplate code, helps to prevent memory leaks and simplifies async data loading into your UI. I can’t say that it brings absolutely new approaches for solving these issues, but, finally, we have a formal, single and official direction.

AAC provides some abstractions to deal with Android lifecycle:

  • LifecycleOwner
  • LiveData
  • ViewModel

The main benefit is the fact that our UI components, like TextView or RecycleView, observe LiveData, which, in turn, observes the lifecycle of an Activity or Fragment, using a LifecycleObserver.

Combination of these components solves main challenges faced by Android developers, such as boilerplate code or modular. To explore and check an example of this concept, I decided to create the sample project. It just gets a list of repositories from Github and shows one using RecyclerView.

As you can see, it handles configuration changes without any problems, and an Activity looks very simple:

class ReposActivity : BaseLifecycleActivity<ReposViewModel>(), SwipeRefreshLayout.OnRefreshListener {

override val viewModelClass = ReposViewModel::class.java

private val rv by unsafeLazy {
 findViewById<RecyclerView>(R.id.rv) 
}

private val vRefresh by unsafeLazy {
 findViewById<SwipeRefreshLayout>(R.id.lRefresh) 
}

private val adapter = ReposAdapter()

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_repos)

rv.setHasFixedSize(true)

rv.adapter = adapter

vRefresh.setOnRefreshListener(this)

 if (savedInstanceState == null) {

 viewModel.setOrganization("yalantis")

}

observeLiveData()
  
}

private fun observeLiveData() {

viewModel.isLoadingLiveData.observe(this, Observer<Boolean> {

 it?.let {
 vRefresh.isRefreshing = it 
}

}
)

viewModel.reposLiveData.observe(this, Observer<List<Repo>> {

 it?.let {
 adapter.dataSource = it 
}

}
)

viewModel.throwableLiveData.observe(this, Observer<Throwable> {

 it?.let {
 Snackbar.make(rv, it.localizedMessage, Snackbar.LENGTH_LONG).show() 
}

}
)
  
}

override fun onRefresh() {

viewModel.setOrganization("yalantis")
  
}
 
}

How you have probably noticed, our activity assumes minimum responsibilities. ReposViewModel holds state and view data in the following way:

open class ReposViewModel(application: Application?) : AndroidViewModel(application) {

private val organizationLiveData = MutableLiveData<String>()

val resultLiveData = ReposLiveData().apply {

this.addSource(organizationLiveData) {
 it?.let {
 this.organization = it 
}
 
}

  
}

val isLoadingLiveData = MediatorLiveData<Boolean>().apply {

this.addSource(resultLiveData) {
 this.value = false 
}

  
}

val throwableLiveData = MediatorLiveData<Throwable>().apply {

this.addSource(resultLiveData) {
 it?.second?.let {
 this.value = it 
}
 
}

  
}

val reposLiveData = MediatorLiveData<List<Repo>>().apply {

this.addSource(resultLiveData) {
 it?.first?.let {
 this.value = it 
}
 
}

  
}

fun setOrganization(organization: String) {

organizationLiveData.value = organization

isLoadingLiveData.value = true
  
}
  
}

Testability

@RunWith(AndroidJUnit4::class) class SampleInstrumentedTest {

@get:Rule
  val activityRule = ActivityTestRule<ReposActivity>(ReposActivity::class.java, true, true)

private var viewModel: ReposViewModel? = null

@Before
  fun init() {

viewModel = ViewModelProviders.of(activityRule.activity).get(ReposViewModel::class.java)
  
}

@Test
  fun testNotNull() {

activityRule.activity.runOnUiThread {

 viewModel?.setOrganization("yalantis")

 viewModel?.reposLiveData?.observe(activityRule.activity, Observer<List<Repo>> {

 assertNotNull(it)

 
}
)

}

  
}
 
}

Resources

HtmlSpanner allows you full control over how tags are rendered and gives you all the data about the location of a tag in the text. This allows proper handling of anchors, tables, numbered lists and unordered lists.

Dividers is a Android library to easily create separators for your RecyclerViews. It supports a wide range dividers from a simple one that apply all your items to system of selectors to apply different styles to each item.

Takt is Android library for measuring the FPS using Choreographer.

Material bootstrap for Android development like Bootstrap or Foundation for web.

Quick Android Review Kit - This tool is designed to look for several security related Android application vulnerabilities, either in source code or packaged APKs. The tool is also capable of creating "Proof-of-Concept" deployable APKs and/or ADB commands, capable of exploiting many of the vulnerabilities it finds. There is no need to root the test device, as this tool focuses on vulnerabilities that can be exploited under otherwise secure conditions.

An interactive view with water waves flowing like in a washing machine.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes