Skip to content

Commit

Permalink
feat: LocalEvent optimize
Browse files Browse the repository at this point in the history
Signed-off-by: Hu Shenghao <[email protected]>
  • Loading branch information
hushenghao committed Dec 2, 2024
1 parent 587ae07 commit 375ead7
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
50 changes: 50 additions & 0 deletions basic/src/main/java/com/dede/android_eggs/util/GcWatcher.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.dede.android_eggs.util

import java.lang.ref.WeakReference

/**
* GC Watcher
*
* @see [com.android.internal.os.BinderInternal]
*/
class GcWatcher private constructor() {

companion object {

private val sInstance = GcWatcher()

private val sGcWatchers: ArrayList<Runnable> = ArrayList()
private var sTempWatchers: Array<Runnable?> = emptyArray()

private var sGcWatcherRef: WeakReference<GcWatcherObj> = WeakReference(GcWatcherObj())

fun get(): GcWatcher {
return sInstance
}
}

@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
private class GcWatcherObj : Object() {
override fun finalize() {
synchronized(sGcWatchers) {
sTempWatchers = sGcWatchers.toArray(sTempWatchers)
}
for (gcWatcher in sTempWatchers) {
gcWatcher?.run()
}
sGcWatcherRef = WeakReference(GcWatcherObj())
}
}

fun addWatcher(watcher: Runnable) {
synchronized(sGcWatchers) {
sGcWatchers.add(watcher)
}
}

fun removeWatcher(watcher: Runnable) {
synchronized(sGcWatchers) {
sGcWatchers.remove(watcher)
}
}
}
18 changes: 18 additions & 0 deletions basic/src/main/java/com/dede/android_eggs/util/LocalEvent.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.dede.android_eggs.util

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
Expand All @@ -24,6 +25,23 @@ object LocalEvent {
return liveData
}

init {
GcWatcher.get().addWatcher { trim() }
}

private fun trim() {
var count = 0
val keys = localEventLiveDataMap.keys
for (key in keys) {
val liveData = localEventLiveDataMap[key] ?: continue
if (!liveData.hasObservers()) {
localEventLiveDataMap.remove(key)
count++
}
}
Log.i("LocalEvent", "trim: %d".format(count))
}

fun poster(): Poster {
return Poster()
}
Expand Down

0 comments on commit 375ead7

Please sign in to comment.