@@ -231,19 +231,38 @@ class MainActivity : ComponentActivity() {
231231 return parakeetModule!!
232232 }
233233
234- // Settings changed or first load — close the old module and create a new one.
235- parakeetModule?.close()
234+ // Settings changed or first load — construct the new module first,
235+ // then swap it in and close the old one only after successful creation.
236+ val oldModule = parakeetModule
237+
238+ // Clear cached module and paths so a failed load never returns a closed or stale module.
239+ parakeetModule = null
240+ loadedModelPath = null
241+ loadedTokenizerPath = null
242+ loadedDataPath = null
243+
236244 Log .v(TAG , " Loading model: ${settings.modelPath} " )
237- val module = ParakeetModule (
238- modelPath = settings.modelPath,
239- tokenizerPath = settings.tokenizerPath,
240- dataPath = dataPath
241- )
242- parakeetModule = module
245+ val newModule = try {
246+ ParakeetModule (
247+ modelPath = settings.modelPath,
248+ tokenizerPath = settings.tokenizerPath,
249+ dataPath = dataPath
250+ )
251+ } catch (e: Exception ) {
252+ // Leave cache cleared; do not close the old module here since it may still be in use.
253+ throw e
254+ }
255+
256+ // Successfully created the new module; now it is safe to close the old one
257+ // and update the cached references and paths.
258+ oldModule?.close()
259+
260+ parakeetModule = newModule
243261 loadedModelPath = settings.modelPath
244262 loadedTokenizerPath = settings.tokenizerPath
245263 loadedDataPath = dataPath
246- return module
264+
265+ return newModule
247266 }
248267
249268 /* *
0 commit comments