Throughout the years that I’ve been developing and reviewing Android applications, most of them had problems dealing with configuration changes: the application makes a network request/computation task and if the device rotates it’s all gone and we need to restart those tasks.

Pre-ViewModel solutions

While some applications simply don’t allow configuration changes, others try to solve it in different ways:

Singleton pattern/Component living on a higher scope which keeps track of these events

Fragment.setRetainInstance(boolean)

Using Loaders

These were the most common patterns that I’ve seen to solve this problem. One that worked really well for me was using Loaders. They survive configuration changes so any data that they hold also survives. This might include Presenters/Controllers/anything really. To know more how you can implement a component that survives configuration changes I recommend reading this great article by Ian Lake.

So we already have the problem solved why bother? Well there are some keypoints that you need to be aware before starting using Loaders:

They involve quite some boilerplate to set them up. Well maybe not that much but we need to consider the lifecycle of the Loader itself (on top of the Activity/Fragment lifecycle)

class PresenterLoader<T : BasePresenter<*>>(context: Context, private val creator: () -> T) : Loader<T>(context) {

private var presenter: T? = null



override fun onStartLoading() {

presenter?.let { deliverResult(presenter); return }

forceLoad()

}



override fun onForceLoad() {

presenter = creator()

deliverResult(presenter)

}



override fun onReset() {

presenter?.onDestroyed()

presenter = null

}

}

2. They are attached to the Activity/Fragment lifecycle but in a restrictive way. As Ian Lake mentions in the article:

In almost every case, there’s only one method you’ll need to call: initLoader(). This is generally called in onCreate() or onActivityCreated()

Given this, Loaders are a great option to store components that survive configuration changes but they also come with the drawbacks of dealing with an additional lifecycle and the knowledge on how it attaches to the current Activity/Fragment/View lifecycle.