Factor out common traversal code in observers

Summary: Each observer was doing a similar job of traversing, and setting up child observers and its easy to not clean up child observers in some cases. This provides a helper utility for the common use case

Reviewed By: lblasa

Differential Revision: D39466930

fbshipit-source-id: e74ae5c3709297b73c020cd148a0485ac9fc0f8f
This commit is contained in:
Luke De Feo
2022-09-13 11:05:42 -07:00
committed by Facebook GitHub Bot
parent a0ee774159
commit 4341cbdf3d
4 changed files with 64 additions and 44 deletions

View File

@@ -1,42 +1,37 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.flipper.plugins.uidebugger.litho
import com.facebook.flipper.plugins.uidebugger.SubtreeUpdate
import android.util.Log
import com.facebook.flipper.plugins.uidebugger.LogTag
import com.facebook.flipper.plugins.uidebugger.TreeObserver
import com.facebook.flipper.plugins.uidebugger.core.Context
import com.facebook.flipper.plugins.uidebugger.identityHashCode
import com.facebook.flipper.plugins.uidebugger.observers.TreeObserverBuilder
import com.facebook.litho.LithoView
class LithoViewTreeObserver(val context: Context) : TreeObserver<LithoView>() {
override val type = "Litho"
var nodeRef: LithoView? = null
override fun subscribe(node: Any) {
node as LithoView
nodeRef = node
nodeRef = node as LithoView
val listener: (view: LithoView) -> Unit = {
val start = System.currentTimeMillis()
val (nodes, skipped) = context.layoutTraversal.traverse(it)
for (observerRoot in skipped) {
if (!children.containsKey(observerRoot.identityHashCode())) {
val observer = context.observerFactory.createObserver(observerRoot, context)!!
observer.subscribe(observerRoot)
children[observerRoot.identityHashCode()] = observer
}
}
context.treeObserverManager.emit(
SubtreeUpdate("Litho", nodes, start, System.currentTimeMillis()))
}
val listener: (view: LithoView) -> Unit = { traverseAndSend(context, node) }
node.setOnDirtyMountListener(listener)
listener(node)
}
override fun unsubscribe() {
Log.i(LogTag, "Unsubscribing from litho view")
nodeRef?.setOnDirtyMountListener(null)
nodeRef = null
}