I develop a K/N Multiplatform module and using the latest Kotlin 1.4.21. I found it often shows the following error message and terminate the app (crash) when I deinit this object:
Memory leaks detected, x objects leaked!
Use `Platform.isMemoryLeakCheckerActive = false` to avoid this check.
I cannot not figure out the reason of the memory leak, and following is my kotlin class using callback function:
class Detector(private val onEventDetected: ((event: Event) -> Unit)?) {
fun processData(data: Data) {
detectEvent(data)
}
private fun detectEvent(data: Data) {
if (...) {
... // some logic
onEventDetected?.invoke(event)
}
}
}
I found when I comment out the onEventDetected?.invoke(event), the error message got disappear. How can I implement the class to forbidden the memory leak issue?
Updated: Dec 21, 2020
I add WeakReference for different platforms:
// Common module
expect class WeakReference<T : Any>(referred: T) {
fun clear()
fun get(): T?
}
// For JVM
actual typealias WeakReference<T> = java.lang.ref.WeakReference<T>
// For iOS Native
actual typealias WeakReference<T> = kotlin.native.ref.WeakReference<T>
And update the class:
class Detector(private val onEventDetected: ((event: WeakReference<Event>) -> Unit)?) {
fun processData(data: Data) {
detectEvent(data)
}
private fun detectEvent(data: Data) {
if (...) {
... // some logic
onEventDetected?.invoke(WeakReference(event))
}
}
}
But the Memory leaks detected issues still happened. There is no clue to solve this problem :(