Category

Android

Android LiveData & ViewModel

If you missed it, there were some awesome announcements about Android at Google I/O 2017. Say hello to Android Architecture Components.

Architecture Components.

A new collection of libraries that help you design robust, testable, and maintainable apps. Two main pain points addressed by Architecture Components are:

  1. Help manage UI components lifecycle.
  2. Persistent data during configuration changes.

We’ll briefly take a look at the main components then jump into some code.

There are 3 main components:

  1. Room
  2. ViewModel
  3. LiveData

LiveData: allows you to observe changes to data across multiple components of your app without creating explicit, rigid dependency paths between them. LiveData respects the complex life cycles of your app components, including activities, fragments, services, or any LifecycleOwner defined in your app.

ViewModel: Provides a way to create and retrieve objects that are bound to a specific lifecycle. A ViewModeltypically stores the state of a view’s data and communicates with other components, such as data repositories or the domain layer which handles business logic. To read an introductory guide to this topic, see ViewModel. It exposes the required data and interested parties can listen to it.

Room: is a persistence library that makes it easier to work with SQLiteDatabase objects in your app, decreasing the amount of boilerplate code and verifying SQL queries at compile time.

Project Overview

To demonstrate all we’ve just gone through, we’ll build an app in various stages, by the end of this blog-post series, we’ll have built an app that fetches data from Github Api. We’ll use MVVM architecture in this tutorial.  As mentioned earlier, ViewModel exposes the required data and interested parties can listen to it. 

Getting Started

The source code for this project can be found on GitHub.

I am using Android Studio 3.0 Preview for this project. If you don’t have it, go ahead and download it. You can run it alongside with other versions so don’t panic. ?

Add the following architecture dependencies to your app level build.gradle file.

Now that we have that setup, let’s create the ViewModel class. For now, we will hard code some data, just to get us started. We’ll use a handler to simulate a delay which ideally happens when loading data from a server.

Let’s look at the code before we move on.

ViewModel Code Breakdown

  • Every ViewModel class must extend the ViewModel class. If your ViewModel needs the application context, it must extend AndroidViewModel. The ViewModel will contain all the data needed for our Activity.
  • Our LiveDatanow completely encapsulates the loading process, loading the data only once. This is handled by getGitUserNames().
  • setvalue() cannot be done in background thread it must be done in main thread only.

Final Step: Connecting UI to ViewModel

Now that we have the ViewModel class, we can use it in our activity by creating an instance of it. This will allow us to have access to getGitUserNames().

MainActivity Code Breakdown

  • We have to useLifecycleActivity because it provides us with the state of the lifecycle.
  • If you see functions with Arrows, don’t panic. The are Lambda Expressions. You can check out a previous article on this.

That’s it. We are done. Pretty simple. Right??

 

Take note of when the orientation of the device changes. Data does not get reloaded again.? Because we used ViewModel along with LiveData class to store data during orientation change, new instance of activity will be created but the data won’t be downloaded again. ViewModel will provide the most recent available data.

 

What Next

This is not over. In the next articles, we’ll cover:

  1. Dependency Injection.
  2. Fetching data using Retrofit.
  3. Room.
  4. Unit Testing.
  5. ….

 

Stay tuned for more posts.

The source code for this project can be found on GitHub.

RxJava + Android

In the previous post we talked about  Lambdas on Android.

In this article, we are going to explore the amazing world of  Reactive Programming.  This is a combination of the best ideas from the Observer pattern, the Iterator pattern, and functional programming. Chances are you’ve heard of RxJava. RxJava is a Java VM implementation of ReactiveX (Reactive Extensions): a library for composing asynchronous and event-based programs by using observable sequences.

Why Consider RxJava?

As a developer you don’t have to worry too much about the details of how to perform operations that should occur on different threads. RxJava simplifies development because it raises the level of abstraction around threading. If you have done threading, it can be a nightmare. If not correctly implemented, can cause some of the most difficult bugs to debug and fix.

 

Problem.

So let’s say you want to compare if two passwords match. We’d need to implement .addTextChangedListener() to listen for any changes on the EditText then compare if the passwords match.

67509492

 

This how the above would look.

Let’s Go Rx.

1. The Observable. We’ll implement an Observable which will emit changes. An Observable is the stream abstraction in RxJava. It is similar to an Iterator in that, given a sequence, it iterates through and produces those items in an orderly fashion.

Observable passwordObservable = RxTextView.textChanges(mPasswordEditText);

2. Subscription The Subscribe operator is the glue that connects an observer to an Observable. In order for an observer to see the items being emitted by an Observable. In English, the Subscription will replace .addTextChangedListener().

.observeOn() : This will allow us to specify where we want us to run the operation, in this case main thread.

.debounce(): This will enable to wait for x time before comparing items.

.doOnNext(): We’ll use this to hide the error if the password is correct. Putting it all together

3. Observable.combineLatest()

This combines the latest item emitted by each Observable and helps us compare the observables.

 

 

If the passwords match, the error message on confirm password is removed & register button is enabled.

Final Result

 

RxJava

The source code is available on GitHub

In the next series we’ll implement Realm… Go forth an Rx-ify the world.

1-4QWcaiW5fMkOjH26Q9cWBQ