Skip to main content

An LLM client that respects the Android lifecycle

Updated 2 min readMarkdown

Holding the client

Server SDKs can assume a lot: a long-lived process, a secret store, a thread pool nobody watches. An Android client assumes none of that. The process can die, the screen can rotate mid-request, the API key sits inside an artifact anyone can download, and the main thread is one blocked call away from a janky app.

The nRouter Android SDK (https://nrouter.ai/docs/sdks/android) is the gateway's client re-cut for those constraints. It ships as an AAR — ai.nrouter:nrouter-sdk-android:3.1.2, minSdk 21 — with main-thread-safe coroutine bindings and lifecycle dispatching. The guide's pattern is an AndroidViewModel holding the client: NRouterAndroid.create(app.applicationContext, key), with calls launched in viewModelScope. The ViewModel survives the rotation; viewModelScope cancels the work when the screen is finished. Nothing blocks the UI thread.

Metadata is part of the result

Every completion returns two things: the response body, and meta, extracted from the gateway's response headers. result.meta.cost is the one you'll use most — per-call cost as a typed field, ready to log or budget against, no header scraping.

Streaming as a cold Flow

messagesStream returns a cold Flow. It does nothing until collected, and collecting inside viewModelScope binds the stream to the screen's lifecycle. Each chunk exposes delta only: client.messagesStream(request).collect { chunk -> bubble += chunk.delta }. That's the whole streaming API, and on Android that's a feature.

Keys: the guide's one hard rule

In production, pass short-lived virtual keys minted by your backend rather than embedding static keys in APK binaries. For tests and local CLI work the client falls back to the NROUTER_API_KEY environment variable. The split is deliberate — the convenient path exists for development, the safe path is documented for production.

Per-call routing, typed errors

The request JSON carries the routing controls: model "nrouter/auto" with "nrouter_optimize" (quality | balanced | cost) and "nrouter_cost_band" (low | mid | high, under cost only). Refusals map to typed exceptions: NRouterError.Request 400 (invalid parameters or unsatisfied cost band), GuardrailBlocked 400, Authentication 401, Credit 402 (balance exhausted or budget ceiling hit), RateLimit 429, Service 503. On mobile, the 401/402/429 distinction drives real UI decisions — refresh the key, show a paywall state, or back off quietly.

The Android SDK guide (https://nrouter.ai/docs/sdks/android) has the complete setup, including the Gradle block and the full streaming example.

1 view

About the author

  • nRouter is a managed LLM gateway: one OpenAI-compatible API key, with smart routing, automatic failover, guardrails, virtual keys, and per-key budgets enforced in the request path.

No comments yet. Be the first to comment.

More from this blog