Skip to content

Commit e35b4a2

Browse files
committed
fix(startup): load libsodium synchronously to prevent race with Compose
LibSodiumInitializer was wrapping initializeWithCallback in a CoroutineScope(Dispatchers.IO).launch, making native lib loading fire-and-forget. On slower devices, Compose could attach and call Box.keypair() before the background coroutine finished, crashing with: UninitializedPropertyAccessException: lateinit property sodiumJna has not been initialized Initializer.create() runs on the main thread at app startup, and on Android initializeWithCallback is synchronous (JNA Native.load + sodium_init), so calling it directly guarantees sodium is ready before any downstream caller touches it.
1 parent e08b2d3 commit e35b4a2

1 file changed

Lines changed: 8 additions & 7 deletions

File tree

apps/flipcash/app/src/main/kotlin/com/flipcash/app/internal/startup/LibSodiumInitializer.kt

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,17 @@ import androidx.startup.Initializer
55
import com.getcode.utils.TraceType
66
import com.getcode.utils.trace
77
import com.ionspin.kotlin.crypto.LibsodiumInitializer
8-
import kotlinx.coroutines.CoroutineScope
9-
import kotlinx.coroutines.Dispatchers
10-
import kotlinx.coroutines.launch
118

129
class LibSodiumInitializer: Initializer<Unit> {
1310
override fun create(context: Context) {
14-
CoroutineScope(Dispatchers.IO).launch {
15-
LibsodiumInitializer.initializeWithCallback {
16-
trace("libsodium initialized", type = TraceType.Process)
17-
}
11+
// Must run synchronously on the main thread: Initializer.create runs at app
12+
// startup before any UI is attached, and downstream callers (e.g. Box.keypair)
13+
// hit sodiumJna as soon as Compose attaches. Dispatching this to a background
14+
// coroutine creates a race where the native lib may not be loaded in time.
15+
// On Android, initializeWithCallback is synchronous — it loads the .so via
16+
// JNA, calls sodium_init, then invokes the callback on the same thread.
17+
LibsodiumInitializer.initializeWithCallback {
18+
trace("libsodium initialized", type = TraceType.Process)
1819
}
1920
}
2021

0 commit comments

Comments
 (0)