top of page

Handling background work on Android

Losing context for our background tasks on changing orientation is a popular problem. Web is full of examples on how to handle this topic using AsyncTasks or Services.

In this post we will see how to implement this functionality in separation from android framework. This may be helpful when you want to treat android as a layer of data presentation and keep app logic framework-independant.

This blog post was heavilty influenced by Michał Charmas and his android clean architecture shopping list.

As a reference I also used Chiu-Ki Chan example for Dagger2 + Mockito.

As it was not so trivial to analyze shopping list I decided to break this code into smaller chunks.

See the whole code on : RotateMe

RotateMe project requirements:

1 Sample App presents list of random texts on UI on "Go" button click. 2 Random texts are provided by backgroud task. 3 If user rotates the screen while fetching the data, as soon as ui is attached again it displays what we fetched. 4 Code is testable

In the project I will use Dagger 2, basic rxJava, Mockito.

For the example simplicity I did not divided it into separate modules as in shopping list example.

Some assumptions:

UI - Activity presenting data. No additional logic. Presenter - ui backend containing use cases (business logic) and handling user interactions UseCase - Single business logic action. Data - Some data that our app operates on.

You will find the code separated into packages with the same naming convention.

Presenter - the center of interest

First class to notice is abstract BasePresenter.

It handles UI being attached and detached

and holds Queue of actions that should be perfomed on UI.

It is extended by MainActivityPresenter which contains:

GetDataUseCase - well.. a use case UseCaseExecutor - interface for executing useCases. Why interface?

It will be implemented by:

AsyncUseCaseExecutor which will execute useCase asynchronously and deliver results to android's MainThread.

SyncUseCaseExecutor that does the same job synchonously for the sake of easy testing.

Both classes use rxJava to execute usecases.

Simplifying the code came with the drawback: If the usecase finish executing riiiight before we rotate - it can update UI that will be scrapped in a second. In shopping list example you can see the usage of redeliverOnAttachment flag to overcome this problem.

Recent Posts
Archive
Search By Tags
Nie ma jeszcze tagów.
bottom of page