Skip to content

Instantly share code, notes, and snippets.

@rharter
Last active August 9, 2022 14:58
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rharter/7871d08e9375ba2b001f20947f18868e to your computer and use it in GitHub Desktop.
Save rharter/7871d08e9375ba2b001f20947f18868e to your computer and use it in GitHub Desktop.
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()
}
}
@pawegio
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. :)

@cbeyls
Copy link

cbeyls commented Jun 7, 2020

Hello Ryan, thank you for sharing this code.

If I'm not mistaken, the current implementation would only work for a single scoped value per Fragment or Activity.
Because of type erasure, the ViewModelStore can not distinguish a ScopeViewModel<X> from a ScopeViewModel<Y>.
So I would recommend that you also pass the field name as key argument when you call the ViewModelProvider:

val viewModel = ViewModelProvider(store, factory).get(fieldName, ScopeViewModel::class.java)

Also, you could allow nullable values by just changing the type of cached to Any?

@thegarlynch
Copy link

how do i use dagger in this ?

@mochadwi
Copy link

mochadwi commented Dec 16, 2020

i'm curious about your statements about ViewModel is tightly coupled with Android framework

but your whole imports is dependent with androidx.lifecycle.* wouldn't this means using this approach also on kotlin multiplatform needs to coupled with android framework?

Unfortunately, I also can't find your samples on kotlin multiplatform to use this gist?

Did you mean, you were replacing the ViewModel in business logic with *Presenter so the Presenter class is shared among platform?

That way, you can still leverages ViewModel solutions in Android without adding much logic/details in the ViewModel itself

@rharter

@rharter
Copy link
Author

rharter commented Dec 17, 2020

Yeah, this code that scopes objects to the Android Lifecycle is inherently coupled to the Android platform, since no other platform shares that lifecycle. The benefit of this is that your business logic class, a Presenter or view model (not AndeoidX View model) is no longer tightly coupled to the Android framework.

That's the code you'd want to share, anyway. There's no point sharing this code, which is glue to connect the shared code to the Framework, on other platforms, since they have their own glue code.

@mochadwi
Copy link

Awesome! Thanks for explaining @rharter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment