Skip to content

Commit c56420b

Browse files
authored
android: lazily init app in Client (#563)
-Lazily init app in Client to ensure that we aren't trying to make any local API calls before app has been initialized. -Add @volatile to ensure that isInitialized is always visible across threads and uses the updated value Updates tailscale/tailscale#14125 Signed-off-by: kari-ts <[email protected]>
1 parent ed8a1b3 commit c56420b

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

android/src/main/java/com/tailscale/ipn/App.kt

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,13 @@ class App : UninitializedApp(), libtailscale.AppContext, ViewModelStoreOwner {
9090
Log.d(s, s1)
9191
}
9292

93+
fun getLibtailscaleApp(): libtailscale.Application {
94+
if (!isInitialized) {
95+
initOnce() // Calls the synchronized initialization logic
96+
}
97+
return app
98+
}
99+
93100
override fun onCreate() {
94101
super.onCreate()
95102
appInstance = this
@@ -119,15 +126,19 @@ class App : UninitializedApp(), libtailscale.AppContext, ViewModelStoreOwner {
119126
viewModelStore.clear()
120127
}
121128

122-
private var isInitialized = false
129+
@Volatile private var isInitialized = false
123130

124131
@Synchronized
125132
private fun initOnce() {
126133
if (isInitialized) {
127134
return
128135
}
136+
137+
initializeApp()
129138
isInitialized = true
139+
}
130140

141+
private fun initializeApp() {
131142
val dataDir = this.filesDir.absolutePath
132143

133144
// Set this to enable direct mode for taildrop whereby downloads will be saved directly

android/src/main/java/com/tailscale/ipn/ui/localapi/Client.kt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import com.tailscale.ipn.ui.model.StableNodeID
1313
import com.tailscale.ipn.ui.model.Tailcfg
1414
import com.tailscale.ipn.ui.util.InputStreamAdapter
1515
import com.tailscale.ipn.util.TSLog
16+
import com.tailscale.ipn.App
1617
import kotlinx.coroutines.CoroutineScope
1718
import kotlinx.coroutines.Dispatchers
1819
import kotlinx.coroutines.launch
@@ -67,6 +68,11 @@ typealias PingResultHandler = (Result<IpnState.PingResult>) -> Unit
6768
class Client(private val scope: CoroutineScope) {
6869
private val TAG = Client::class.simpleName
6970

71+
// Access libtailscale.Application lazily
72+
private val app: libtailscale.Application by lazy {
73+
App.get().getLibtailscaleApp()
74+
}
75+
7076
fun start(options: Ipn.Options, responseHandler: (Result<Unit>) -> Unit) {
7177
val body = Json.encodeToString(options).toByteArray()
7278
return post(Endpoint.START, body, responseHandler = responseHandler)

0 commit comments

Comments
 (0)