Best Practices
Handling Process Death on Android
The Problem
The Solution: Application-Scope Monitoring
1
Create a Singleton Manager
// commonMain
object LocationManager {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
fun monitor() {
// 1. Initialize Anchor
Anchor.init { /* ... config ... */ }
// 2. Start collecting immediately
scope.launch {
Anchor.locationFlow.collect { location ->
// Save to DB / Send to API
// This runs even if UI is dead
Repository.save(location)
}
}
// 3. Resume tracking if needed
// If the app was killed while tracking, we should ensure the engine is started.
if (shouldBeTracking()) {
scope.launch {
if (Anchor.isReady) Anchor.startTracking()
}
}
}
}