Skip to content

Instantly share code, notes, and snippets.

@edwardharks
Created September 27, 2017 09:12
Show Gist options
  • Save edwardharks/bc3a7173a8ac02324d2b6ecf1a4a94e7 to your computer and use it in GitHub Desktop.
Save edwardharks/bc3a7173a8ac02324d2b6ecf1a4a94e7 to your computer and use it in GitHub Desktop.
/*
* Copyright 2017 Shazam Entertainment Limited
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
fun <T> View.viewDependency(initializer: () -> T): ViewDependency<T> =
if (isInEditMode) {
EditModeViewDependency(this, initializer)
} else {
ImmediateViewDependency(initializer)
}
fun <T> View.lazyViewDependency(initializer: () -> T): ViewDependency<T> =
if (isInEditMode) {
EditModeViewDependency(this, initializer)
} else {
LazyViewDependency(initializer)
}
interface ViewDependency<out T> : ReadOnlyProperty<View, T> {
val value: T
override fun getValue(thisRef: View, property: KProperty<*>): T = value
}
private class LazyViewDependency<out T>(initializer: () -> T) : ViewDependency<T> {
override val value: T by lazy(initializer)
}
private class ImmediateViewDependency<out T>(initializer: () -> T) : ViewDependency<T> {
override val value: T = initializer()
}
private class EditModeViewDependency<out T>(val view: View, val initializer: () -> T) : ViewDependency<T> {
companion object {
private var hasSetFakeApplication = false
}
override val value: T
get() {
ensureFakeApplication()
return initializer.invoke()
}
private fun ensureFakeApplication() {
if (!hasSetFakeApplication) {
ApplicationReference.application = EditModeApplication(view.context)
hasSetFakeApplication = true
}
}
}
@SuppressLint("Registered")
private class EditModeApplication(context: Context) : ShazamApplication() {
init {
attachBaseContext(context)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment