DEV Community

Discussion on: Don’t write Android apps like it’s 2009!

Collapse
 
cjbrooks12 profile image
Casey Brooks

It definitely does not mean using a single file with thousands of lines of code. In fact, quite the opposite.

In the past, everything was dumped into an Activity. Handling UI events, formatting data to display on the screen, inserting data into a database, calling to an external service.... everything. It was horrible to maintain, nearly impossible to test, and extremely prone to getting into invalid states due to too much stuff being managed in the wrong place and getting messed with because of the Activity lifecycle. Activities were expected to handle app state, navigation flows to other activities, UI, interaction, and data processing. Clearly no separation of concerns.

The first steps toward breaking up those activities were Fragments, but people tended to just move all that stuff from an Activity into a Fragment. Now, the problem was compounded because you have both the Activity and Fragment lifecycles to worry about. But a single Fragment inside in Activity is no bueno, and kinda defeats the purpose they were created for. This period of time is why so many people are still very soured on Fragments (including myself; I haven't quite made the jump to the NavigationComponent yet).

The way to go about it now should be to utilize the NavigationComponent to swap Fragments in-and-out, and use ViewModels for holding and managing the data needed between those fragments. Now, an Activity should host a NavigationComponent. Fragments handle UI and interaction. ViewModels handle app state. Data processing should be done in RxJava or Kotlin Coroutines, typically in dedicated service classes. Overall, a much better separation of concerns.

Collapse
 
mgazar_ profile image
Mostafa Gazar

Excellent explanation and a great brief history of how things used to be in the Android world 👍