Skip to content

Instantly share code, notes, and snippets.

@Kyle-Ye
Last active November 13, 2024 14:19
Show Gist options
  • Save Kyle-Ye/85284949f901360f7b5db1a4d1d5d0ac to your computer and use it in GitHub Desktop.
Save Kyle-Ye/85284949f901360f7b5db1a4d1d5d0ac to your computer and use it in GitHub Desktop.
Workaround for UICollectionViewCell+RCTRootView
import Dispatch
import Foundation
import UIKit
extension DispatchQueue {
/// Run the action immediately if it's on the main thread, otherwise dispatch it to the main thread asynchronously.
public static func onMainThread(_ action: @escaping () -> Void) {
if Thread.isMainThread {
action()
} else {
DispatchQueue.main.async {
action()
}
}
}
/// Run the action immediately if it's on the main queue, otherwise dispatch it to the main queue asynchronously.
public static func onMainQueue(_ action: @escaping () -> Void) {
if Thread.isMainThread && DispatchQueue.currentQueueLabel == DispatchQueue.main.label {
action()
} else {
DispatchQueue.main.async {
action()
}
}
}
private static var currentQueueLabel: String {
let label = __dispatch_queue_get_label(nil)
return String(cString: label)
}
}
class DemoCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var rnView: UIView!
private func setupView() {
// RCTRootView expectes to be run on the main queue
DispatchQueue.onMainQueue { [self] in
rnView = RCTRootView(...)
contentView.addSubview(rnView)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment