Last active
August 16, 2020 19:51
-
-
Save adammagana/3413d80c67d42f0d49955d429e659aa7 to your computer and use it in GitHub Desktop.
An Android "Resource Provider" pattern that I often use. Peep the Javadoc comments for details.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.graphics.drawable.Drawable | |
import androidx.annotation.ColorInt | |
import androidx.annotation.ColorRes | |
import androidx.annotation.DrawableRes | |
import androidx.annotation.StringRes | |
import androidx.core.content.ContextCompat | |
import java.lang.ref.WeakReference | |
/** | |
* An interface meant to provide access to a few of Android's most commonly used [Context] methods | |
* without the need to reference a [Context] object directly. E.g. you may want to access resolved | |
* Android resources in a view model without any direct dependency on [Context]. | |
*/ | |
interface ResourceProvider { | |
fun getString(@StringRes id: Int): String | |
fun getString(@StringRes id: Int, vararg formatArgs: Any?): String | |
@ColorInt | |
fun getColor(@ColorRes id: Int): Int | |
fun getDrawable(@DrawableRes id: Int): Drawable? | |
} | |
/** | |
* Spits out a [ResourceProvider] implementation given a [Context]. Holds a [WeakReference] to the | |
* given [Context] to help with GC. | |
*/ | |
fun createResourceProvider(rawContext: Context): ResourceProvider = object : ResourceProvider { | |
private val weakContext = WeakReference(rawContext) | |
private val context: Context | |
get() = weakContext.get()!! | |
override fun getString(@StringRes id: Int): String = context.getString(id) | |
override fun getString(@StringRes id: Int, vararg formatArgs: Any?): String { | |
return context.getString(id, *formatArgs) | |
} | |
@ColorInt | |
override fun getColor(@ColorRes id: Int): Int = ContextCompat.getColor(context, id) | |
override fun getDrawable(@DrawableRes id: Int): Drawable? = ContextCompat.getDrawable(context, id) | |
} | |
/** | |
* A computed property that returns the result of [createResourceProvider]. | |
* | |
* @see createResourceProvider | |
*/ | |
val Context.asResourceProvider: ResourceProvider | |
get() = createResourceProvider(this) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment