Skip to content

Commit f79a4ad

Browse files
committed
Fix main loop
1 parent c24879d commit f79a4ad

File tree

1 file changed

+20
-25
lines changed

1 file changed

+20
-25
lines changed

Demo/app/src/main/swift/MainActivity.swift

Lines changed: 20 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ open class MainActivity: AndroidApp.Activity {
1515
@JavaMethod
1616
open func setRootView(_ view: AndroidView.View?)
1717

18+
static private(set) var shared: MainActivity!
19+
1820
lazy var textView = TextView(self)
1921

2022
lazy var listView = ListView(self)
@@ -37,18 +39,21 @@ extension MainActivity {
3739

3840
private extension MainActivity {
3941

42+
#if os(Android)
43+
typealias MainActor = AndroidMainActor
44+
#endif
45+
4046
func _onCreate() {
47+
MainActivity.shared = self
4148
runAsync()
4249
startMainRunLoop()
4350
setRootView()
4451

4552
// update view on timer
4653
Task { [weak self] in
47-
while let self = self {
54+
while let self {
55+
await self.updateTextView()
4856
try? await Task.sleep(for: .seconds(1))
49-
await MainActor.run { [weak self] in
50-
self?.updateView()
51-
}
5257
}
5358
}
5459
}
@@ -63,34 +68,22 @@ private extension MainActivity {
6368
}
6469
Task {
6570
Self.log("\(self).\(#function) Task Started")
66-
await MainActor.run {
67-
RunLoop.main.run(until: Date() + 0.1)
68-
}
6971
}
7072
}
7173

72-
func runMainThread(_ block: @escaping () -> ()) {
73-
self.runOnUiThread(Runnable(block).as(AndroidJavaLang.Runnable.self))
74-
}
75-
7674
func startMainRunLoop() {
77-
let runnable = Runnable { [weak self] in
78-
// run main loop
79-
RunLoop.main.run(until: Date() + 0.01)
80-
// schedule next
81-
Task { [weak self] in
82-
while let self, let runnable = self.runnable {
83-
try? await Task.sleep(for: .seconds(10))
84-
self.runOnUiThread(runnable)
85-
}
86-
}
75+
#if os(Android)
76+
guard AndroidLooper.setupMainLooper() else {
77+
fatalError("Unable to setup main loop")
8778
}
88-
self.runnable = runnable.as(AndroidJavaLang.Runnable.self)
89-
self.runOnUiThread(self.runnable)
79+
#endif
9080
}
9181

9282
func setRootView() {
93-
setListView()
83+
setRootView(textView)
84+
Task {
85+
await updateTextView()
86+
}
9487
}
9588

9689
func setListView() {
@@ -113,7 +106,9 @@ private extension MainActivity {
113106
setRootView(listView)
114107
}
115108

116-
func updateView() {
109+
@MainActor
110+
func updateTextView() {
111+
log("\(self).\(#function)")
117112
textView.text = "Hello Swift!\n\(Date().formatted(date: .numeric, time: .complete))"
118113
}
119114
}

0 commit comments

Comments
 (0)