Skip to content

Instantly share code, notes, and snippets.

@rharter rharter/Scoped.kt
Last active Jun 2, 2020

Embed
What would you like to do?
A kotlin property delegate to scope any object to an android lifecycle. Blog post at https://ryanharter.com/blog/easy-android-scopes/
import androidx.lifecycle.get
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
/**
* Returns a property delegate to access the wrapped value, which will be retained for the
* duration of the lifecycle of this [ViewModelStoreOwner].
*
* ```
* class MyFragment : Fragment() {
* private val presenter by scoped { MyPresenter() }
*
* override fun onCreate(savedInstanceState: Bundle?) {
* super.onCreate(savedInstanceState)
* presenter.models.collect {
* // ...
* }
* }
* }
* ```
*/
inline fun <reified T> ViewModelStoreOwner.scoped(noinline creator: () -> T): Lazy<T> {
return LazyScopedValue({ viewModelStore }, { ScopeViewModel.Factory(creator) })
}
class ScopeViewModel<V>(
val value: V
) : ViewModel() {
class Factory<V>(val valueFactory: () -> V) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T =
ScopeViewModel(valueFactory()) as? T
?: throw java.lang.IllegalArgumentException("Unknown type")
}
}
class LazyScopedValue<T>(
private val storeProducer: () -> ViewModelStore,
private val factoryProducer: () -> ViewModelProvider.Factory
) : Lazy<T> {
private var cached: Any = NotSet
@Suppress("UNCHECKED_CAST")
override val value: T
get() {
val value = cached
return if (value == NotSet) {
val factory = factoryProducer()
val store = storeProducer()
val viewModel = ViewModelProvider(store, factory).get<ScopeViewModel<T>>()
viewModel.value.also {
cached = it as Any
}
} else {
value as T
}
}
override fun isInitialized() = cached != NotSet
companion object {
private val NotSet = Any()
}
}
@AndroidDeveloperLB

This comment has been minimized.

Copy link

AndroidDeveloperLB commented Mar 15, 2020

What exactly is the point in all this? Why not just get the ViewModel as usual?

@rharter

This comment has been minimized.

Copy link
Owner Author

rharter commented Mar 15, 2020

A ViewModel is tightly coupled to the Android framework (it's a super simple class, yet is an aar dependency with transient deps that are all aars), so can't be used as multiplatform components, in Kotlin only modules, etc. Also, if you have other types of objects, like Dagger Components, that don't need to depend on any Android components, this allows you to easily scope them to a lifecycle without tight coupling.

@AndroidDeveloperLB

This comment has been minimized.

Copy link

AndroidDeveloperLB commented Mar 15, 2020

Oh so it's a more general solution, which works in Kotlin for all platforms? But I think you can make it shorter to use, no?

@rharter

This comment has been minimized.

Copy link
Owner Author

rharter commented Mar 16, 2020

This isn't as much about the presenter as it is about getting the scoping of view models for things other than view models.

That's long been a problem on Android that was initially a develoepr problem, then the AndroidX team took on and solved for ViewModels, but the fact that it's limited to that class, which is tightly coupled, is really arbitrary. This shows that there are use cases for the functionality in a non-coupled way that can leverage the ViewModel to get the same effect without limiting you to Android artifacts.

As far as how to make it shorter to use, this is a single file utility that allows you to use it anywhere in your app with a single line, private val myPresenter: MyPresenter by scoped { MyPresenter() }. If you have an example of how to make that call-site shorter, I'd love if you could share. (If you haven't read the linked blog post, I'd recommend it, I tried to explain all of this. If I didn't make it clear, or you disagree with my assumptions I appreciate you sharing.)

@AndroidDeveloperLB

This comment has been minimized.

Copy link

AndroidDeveloperLB commented Mar 16, 2020

I see. Thank you.
You don't think it's important if all I do is to develop Android apps, though, right?

@rharter

This comment has been minimized.

Copy link
Owner Author

rharter commented Mar 16, 2020

If you don't need it, then no. If you're trying to figure out where to keep things like Dagger scoped Components then this could be helpful, but if you're just doing Android dev with ViewModels then you can just use the by viewModels.

@AndroidDeveloperLB

This comment has been minimized.

Copy link

AndroidDeveloperLB commented Mar 17, 2020

OK thank you.

@pawegio

This comment has been minimized.

Copy link

pawegio commented Mar 18, 2020

Nice solution! The main drawback of ViewModel is that it's part of Android framework and in TDD approach it matters. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.