id: 161 View:category
Tutorials  Architecture
Tutorials  Architecture
The About Process

The ViewModel - your single source of truth

Android developers will have heard about the not-so-quiet revolution introduced at Google I/O 2018 in the form of "JetPack". This is an awesome set of tools, software components and just plain know-how which Google put together to let everyone use the best-practice they've evolved into using themselves. Sure, you can continue with your current frameworks and libraries, it's just that now, zillions of the wheels you might be tempted to reinvent are all laid out for you, and in a way that makes using them a really smart choice.

Jetpack covers UI navigation, tasks, db etc and you can read more about it here. What caught my attention was the way an old problem I've covered before can be tackled, and since you don't need an oracle to see where languages on Android are headed, I chose Kotlin rather than Java. The new killer component is called the ViewModel, and it's purpose it to hold non-UI data which lives independently from the usual app lifecycle. Even better - it can run methods in this new "outside the Activity" place, which means we have a new way to run background tasks. ViewModel predates JetPack, but is considered one of it's central components now.

What's presented here is a way to keep the UI up to date even when the app is backgrounded. There are plenty of ViewModel tutorials around, such as here, here and here, so I'll skim over the basics and focus on the backgrounded UI part, which needs some care to get right.

The source for this project is available on GitHub, and if you just want to run it, allow unknown sources on your Android device and click here.