# Lifecycle & states

> The three states Beekon transitions through, the stop reasons, and how to observe them.

Source: https://docs.getbeekon.com/guide/lifecycle/

Beekon has three states. They are the same on every platform; only the casing follows the language (`Tracking` in Kotlin, `tracking` in Swift).

```plaintext
Idle → Tracking → Stopped(reason)
```

You observe it on the `state` stream. The stream is hot and replays the latest value, so a new subscriber sees the current state at once.

## The states

| State             | Meaning                                                                                               | Live emissions? |
| ----------------- | ----------------------------------------------------------------------------------------------------- | --------------- |
| `Idle`            | Initial state. `configure` may or may not have happened; `start` has not.                             | No              |
| `Tracking`        | Live updates flowing from the OS provider through the gate.                                           | Yes             |
| `Stopped(reason)` | Tracking ended. The reason indicates whether it was user-initiated or forced. Re-enter via `start()`. | No              |

There is no `Starting` state: `start()` suspends, and its completion is the move to `Tracking`. There is no `Paused` state either. A precondition that fails while tracking (permission revoked, location services turned off, the foreground service killed on Android) ends in `Stopped(reason)`, and your app calls `start()` again once the condition is fixed.

## Stop reasons

| Reason                     | When it fires                                                                                                                                                                                                                                                                  |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `User`                     | The host app called `Beekon.stop()`.                                                                                                                                                                                                                                           |
| `PermissionDenied`         | Location permission was revoked or never granted.                                                                                                                                                                                                                              |
| `LocationServicesDisabled` | System-wide location services are turned off. The user can fix it in Settings.                                                                                                                                                                                                 |
| `LocationUnavailable`      | The device has no usable location provider. On Android, Google Play Services is missing or out of date. The user can’t fix it.                                                                                                                                                 |
| `System`                   | The OS stopped tracking and it couldn’t be resumed. On Android, a foreground-service kill (memory pressure, force-stop); on iOS, an unrecoverable internal error such as the on-device database failing to open.                                                               |
| `BackgroundStartDenied`    | Android 12+ only in practice. A start or resume from the background was refused a foreground-service start. The session can still be resumed: see [Transitions](#transitions). Flutter and React Native emit it on Android too. iOS declares it for parity and never emits it. |

All six reasons exist on every platform, with the casing of the host language (`PermissionDenied` on Kotlin, `.permissionDenied` on Swift and Dart, `'permissionDenied'` on React Native).

## Observing state

* Android

  ```kotlin
  // state is a StateFlow: hot, replays the latest value
  val state by Beekon.state.collectAsStateWithLifecycle()


  when (val s = state) {
    is BeekonState.Idle     -> Text("Not started")
    is BeekonState.Tracking -> Text("Live")
    is BeekonState.Stopped  -> Text("Stopped: ${s.reason}")
  }
  ```

* iOS

  ```swift
  Task {
    for await state in await Beekon.shared.state {
      switch state {
      case .idle:                 print("Not started")
      case .tracking:             print("Live")
      case .stopped(let reason):  print("Stopped: \(reason)")
      }
    }
  }
  ```

* Flutter

  ```dart
  Beekon.instance.state.listen((state) {
    switch (state) {
      case Idle():      print('Not started');
      case Tracking():  print('Live');
      case Stopped(:final reason):
        print('Stopped: $reason');
    }
  });
  ```

* React Native

  ```ts
  Beekon.onState((state) => {
    if (state.kind === 'stopped') {
      console.log('Stopped:', state.reason);
    } else {
      console.log(state.kind); // 'idle' | 'tracking'
    }
  });
  ```

## Transitions

```plaintext
   start()              stop() / OS-revocation / system kill
Idle ────────> Tracking ──────────────────────────────> Stopped(reason)
                  ▲                                            │
                  └────────────── start() ─────────────────────┘
```

* `Idle → Tracking`: `start()` succeeds. The first location can arrive immediately.
* `Tracking → Stopped(User)`: the host called `stop()`.
* `Tracking → Stopped(PermissionDenied)`: authorisation was revoked while tracking.
* `Tracking → Stopped(LocationServicesDisabled)`: system location services were turned off.
* `Stopped(LocationUnavailable)`: no usable location provider. On Android, Google Play Services is missing or out of date.
* `Stopped(System)`: on Android, the OS killed the foreground service; on iOS, the SDK hit an unrecoverable internal error (the on-device database could not open).
* `Stopped(BackgroundStartDenied)`: Android only in practice. A resume from the background was refused a foreground-service start (an Android 12+ rule). The saved session is kept, and the next `start()` or `resumeIfNeeded()` recovers it, usually from your `Application.onCreate` when the user next opens the app.
* `Stopped → Tracking`: requires a fresh `start()`. Beekon does not auto-resume when a condition recovers.

`StopReason` may gain values in a minor release. Give every `when` or `switch` an `else` or `default` branch.

Cold-launch resume

`resumeIfNeeded()` restores a session that was tracking before the process died. It does nothing if the user called `stop()` or never started. The SDK reads the last saved `BeekonConfig` from a platform store (`SharedPreferences` on Android, a `UserDefaults` suite on iOS) and re-arms the gate.

* Android: call `Beekon.resumeIfNeeded()` from `Application.onCreate`. The library manifest also registers a receiver for `BOOT_COMPLETED` and `MY_PACKAGE_REPLACED` that resumes an active session and re-arms geofences after a reboot or app update.
* iOS: automatic. The SDK calls `resumeIfNeeded()` itself at launch and each time the app returns to the foreground. After a force-quit, iOS turns off the Significant Location Change wake until the app is next opened.
* Flutter and React Native: call `resumeIfNeeded()` early in startup.

See [Background execution](https://docs.getbeekon.com/guide/background/#cold-launch-resume) for the details.
