Skip to content

Commit 9f5bc58

Browse files
committed
Integrate reset functionality by @paweljaneczek
1 parent 4ed30c5 commit 9f5bc58

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

kotterknife/src/androidTest/kotlin/kotterknife/ViewTest.kt

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,20 @@ class ViewTest {
157157
assertEquals(2, example.name.count())
158158
}
159159

160+
@Test
161+
fun testReset() {
162+
class Example(context: Context) : FrameLayout(context) {
163+
val name: View? by bindOptionalView(1)
164+
}
165+
166+
val example = Example(InstrumentationRegistry.getContext())
167+
example.addView(viewWithId(1))
168+
assertNotNull(example.name)
169+
example.removeAllViews()
170+
KotterKnife.reset(example)
171+
assertNull(example.name)
172+
}
173+
160174
private fun viewWithId(id: Int): View {
161175
val view = View(InstrumentationRegistry.getContext())
162176
view.id = id

kotterknife/src/main/kotlin/kotterknife/KotterKnife.kt

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,16 @@ import android.app.DialogFragment
88
import android.app.Fragment
99
import android.support.v7.widget.RecyclerView.ViewHolder
1010
import android.view.View
11+
import java.util.*
1112
import kotlin.properties.ReadOnlyProperty
1213
import kotlin.reflect.KProperty
1314
import android.support.v4.app.DialogFragment as SupportDialogFragment
1415
import android.support.v4.app.Fragment as SupportFragment
1516

17+
object KotterKnife {
18+
fun reset(target: Any) = LazyRegistry.reset(target)
19+
}
20+
1621
fun <V : View> View.bindView(id: Int)
1722
: ReadOnlyProperty<View, V> = required(id, viewFinder)
1823

@@ -155,10 +160,29 @@ private class Lazy<in T, out V>(private val initializer: (T, KProperty<*>) -> V)
155160
private var value: Any? = EMPTY
156161

157162
override fun getValue(thisRef: T, property: KProperty<*>): V {
163+
LazyRegistry.register(thisRef!!, this)
164+
158165
if (value == EMPTY) {
159166
value = initializer(thisRef, property)
160167
}
168+
161169
@Suppress("UNCHECKED_CAST")
162170
return value as V
163171
}
172+
173+
fun reset() {
174+
value = EMPTY
175+
}
176+
}
177+
178+
private object LazyRegistry {
179+
private val lazyMap = WeakHashMap<Any, MutableCollection<Lazy<*, *>>>()
180+
181+
fun register(target: Any, lazy: Lazy<*, *>) {
182+
lazyMap.getOrPut(target, { Collections.newSetFromMap(WeakHashMap()) }).add(lazy)
183+
}
184+
185+
fun reset(target: Any) {
186+
lazyMap[target]?.forEach { it.reset() }
187+
}
164188
}

0 commit comments

Comments
 (0)