Skip to content

Commit 080d7c4

Browse files
committed
Fix DatabindingPresenter 'leak'
1 parent be055bb commit 080d7c4

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

library/src/main/kotlin/com/otaliastudios/elements/Presenter.kt

+3-3
Original file line numberDiff line numberDiff line change
@@ -180,20 +180,20 @@ public abstract class Presenter<T: Any>(
180180
*/
181181
public class Holder(view: View): RecyclerView.ViewHolder(view) {
182182

183-
private val map: MutableMap<String, Any> = mutableMapOf()
183+
private val map: MutableMap<String, Any?> = mutableMapOf()
184184

185185
/**
186186
* Sets an object to be held by this Holder. Might be a view,
187187
* or any other object you need to attach.
188188
*/
189-
public fun set(key: String, value: Any) { map[key] = value }
189+
public fun set(key: String, value: Any?) { map[key] = value }
190190

191191
/**
192192
* Returns an object that was previously attached to this
193193
* holder using [set].
194194
*/
195195
@Suppress("UNCHECKED_CAST")
196-
public fun <T: Any> get(key: String): T = map[key] as T
196+
public fun <T> get(key: String): T = map[key] as T
197197

198198
/**
199199
* Shorthand for itemViewType.

library/src/main/kotlin/com/otaliastudios/elements/extensions/DataBindingPresenter.kt

+10-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ import android.content.Context
44
import android.view.View
55
import android.view.ViewGroup
66
import androidx.databinding.ViewDataBinding
7+
import androidx.lifecycle.Lifecycle
8+
import androidx.lifecycle.LifecycleObserver
9+
import androidx.lifecycle.OnLifecycleEvent
710
import com.otaliastudios.elements.Element
811
import com.otaliastudios.elements.Page
912
import com.otaliastudios.elements.Presenter
@@ -23,9 +26,15 @@ abstract class DataBindingPresenter<T: Any, DB: ViewDataBinding>(
2326

2427
final override fun onCreate(parent: ViewGroup, elementType: Int): Holder {
2528
val binding = onCreateBinding(parent, elementType)
26-
binding.setLifecycleOwner(this) // Is this the right thing to do?
29+
binding.setLifecycleOwner(this)
2730
val holder = Holder(binding.root)
2831
holder.set("binding", binding)
32+
lifecycle.addObserver(object: LifecycleObserver {
33+
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
34+
fun onDestroy() {
35+
binding.setLifecycleOwner(null)
36+
}
37+
})
2938
return holder
3039
}
3140

0 commit comments

Comments
 (0)