Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 77 ยท Web and Frontend Interview Questions

Android and iOS: Lifecycle, Memory and Architecture Questions

Prepare Android and iOS interviews: activity lifecycle and ViewModel, ARC and retain cycles, threading, Compose and SwiftUI state, MVVM, with runnable stand-ins.

Mobile interviews revolve around three problems that desktop and web developers rarely face. The operating system controls your app's life: it can destroy and recreate screens at any moment (a rotation, low memory, a phone call). Memory is tight and a single leak can get your process killed. And the main thread is sacred: any slow work on it freezes the interface. Almost every question ("What is the Activity lifecycle?", "What is a retain cycle?", "Where does this network call run?") is one of these three in disguise.

Real Android and iOS apps need an emulator or a device, so neither platform's framework can run in the site's code runner. The framework code in this lesson is read-only. The runnable examples are stand-ins in the languages the platforms use: Kotlin (on the site's Kotlin 2.4 runner) models the Android lifecycle and ViewModel, and Swift (Swift 6.3 runner) shows automatic reference counting for real. The full lessons are in the Android and iOS with SwiftUI tutorials, with the languages in Kotlin and Swift. Cross-platform options such as Flutter and React Native have their own questions.

Three mobile problems

Lifecycle The OS destroys and recreates screens.
Memory Leaks get your app killed.
Main thread Never block the UI thread.

Both platforms solve these in similar ways.

1 / 2

What is the Android Activity lifecycle?

Short answer: An Activity is one screen. The system calls lifecycle callbacks as it moves between states: onCreate (build the UI, once), onStart (becoming visible), onResume (in the foreground and interactive), onPause (losing focus, partially visible), onStop (no longer visible), onDestroy (final cleanup). A Fragment has its own lifecycle, nested inside its Activity's, with extra callbacks for its view (onCreateView, onDestroyView).

The question behind the question is configuration changes. Rotating the screen, switching to dark mode or changing the language destroys and recreates the Activity. Any state stored in an ordinary field is lost. You have three tools: onSaveInstanceState (a small Bundle that survives even process death, good for ids and scroll positions), a ViewModel (survives configuration changes but not process death, good for screen state), and persistent storage (Room or DataStore) for real data.

The stand-in below reproduces the callback order and shows what survives a rotation: a plain field is reset, while a value in the ViewModel is kept; pressing Back, which really finishes the screen, clears the ViewModel.

Kotlin Lifecycle callbacks, rotation and a ViewModel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In the real framework the ViewModel store is managed for you, tied to the screen's ViewModelStoreOwner, and the isChangingConfiguration flag is what decides whether onCleared() runs. The part to remember is the result: a rotation keeps the ViewModel and loses plain fields.

Kotlin
// Read-only: a real Android ViewModel with a coroutine and UI state
class ProfileViewModel(private val repository: UserRepository) : ViewModel() {
    private val _state = MutableStateFlow<ProfileState>(ProfileState.Loading)
    val state: StateFlow<ProfileState> = _state

    init {
        viewModelScope.launch {                      // cancelled automatically in onCleared()
            _state.value = try {
                ProfileState.Loaded(repository.load())
            } catch (e: IOException) {
                ProfileState.Error("Could not load profile")
            }
        }
    }
}

Android: other questions you will be asked

  • Why must network or disk work stay off the main thread? Android's main (UI) thread draws the screen, and blocking it for about five seconds causes an ANR (Application Not Responding) dialog. Use coroutines with Dispatchers.IO for blocking work and Dispatchers.Main for UI updates. Updating a view from a background thread throws an exception.
  • What causes memory leaks? Holding a reference to an Activity (or its Context) from something that lives longer, such as a static field, a singleton or a long-running task. Use the application context for app-wide objects, and cancel coroutines in viewModelScope/lifecycleScope.
  • Service versus WorkManager: a foreground service is for work the user is actively aware of (music playback, navigation). WorkManager is for deferrable, guaranteed background work (sync, upload) that survives app restarts and respects battery constraints.
  • Intents: explicit intents name the target component; implicit intents describe an action ("share this text") and the system chooses an app.
  • Views versus Jetpack Compose: the older system builds screens from XML layouts and mutable view objects; Compose is declarative: you describe the UI as functions of state (@Composable), and the framework recomposes when state changes. State lives in remember/rememberSaveable, or in a hoisted ViewModel.
  • Room: an abstraction over SQLite with compile-time checked queries, returning Flow for live updates.
  • Architecture: MVVM (View observes ViewModel state; ViewModel talks to repositories) is the recommended pattern. Mention unidirectional data flow: state flows down, events flow up.
  • Application and process death: the OS may kill your process in the background; restore from saved state, never assume memory survives.

What is ARC, and what is a retain cycle in iOS?

Short answer: Swift uses ARC (automatic reference counting): each class instance has a count of strong references, and when it reaches zero the object is freed and deinit runs. This is deterministic and has no garbage collector pauses. A retain cycle happens when two objects hold strong references to each other (or an object holds a closure that captures it strongly): the counts never reach zero, and the objects leak.

You break cycles with weak (a reference that does not keep the object alive and becomes nil when the object is freed, so it is always an optional var) or unowned (like weak but non-optional; it crashes if used after the object is freed, so use it only when the lifetimes are guaranteed). In closures, use a capture list: [weak self].

This one runs for real on the Swift runner. Look at the first block of output: the objects with the strong cycle are never freed, while with the weak back-reference both are.

Swift ARC, retain cycles and weak references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The last lines show a capture list in action: the closure holds the owner weakly, so setting the variable to nil frees the object immediately and the closure then sees nobody. The final comparison shows why Swift's struct (a value type, copied on assignment) is preferred for simple data and class (a reference type) for shared identity.

iOS: other questions you will be asked

  • View controller lifecycle (UIKit): viewDidLoad (once, view created), viewWillAppear, viewDidAppear, viewWillDisappear, viewDidDisappear. Put one-time setup in viewDidLoad and refresh-on-show work in viewWillAppear.
  • App states: not running, inactive, active, background, suspended. The app can be suspended or terminated in the background, so save state when entering the background.
  • Main thread and concurrency: UI updates must happen on the main thread. Modern Swift uses async/await with actors and @MainActor; older code uses GCD (DispatchQueue.global().async, DispatchQueue.main.async). Swift 6's strict concurrency checks catch data races at compile time.
  • Optionals: a type that may hold nil. Prefer if let, guard let and ?? over force unwrapping with !, which crashes on nil.
  • SwiftUI state: @State owns simple local value state; @Binding is a two-way reference to state owned elsewhere; @StateObject creates and owns an observable object for the view's lifetime, while @ObservedObject only observes one owned by someone else; newer code uses the @Observable macro. The UI is a function of state, like Compose.
  • Value versus reference: structs and enums are copied; classes are shared. Prefer structs.
  • let versus var, protocol-oriented programming, extensions and generics are staple language questions.
  • Persistence: UserDefaults for small settings, Keychain for secrets, Core Data or SwiftData for object graphs, files for documents.

Architecture: MVC, MVVM and clean boundaries

Both platforms started with a thick controller ("Massive View Controller", the fat Activity) and moved toward MVVM: the View shows state and sends events, the ViewModel holds screen state and logic and has no reference to the view, and the Model/Repository handles data. The payoffs are testability (a ViewModel can be unit-tested without a device) and lifecycle safety. Add a repository layer to hide whether data comes from the network or a cache, and use dependency injection (Hilt or Koin on Android, initializer injection on iOS) to swap implementations in tests. A good closing answer: "state flows down, events flow up, and nothing long-lived holds a reference to a short-lived screen".

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A user rotates an Android phone. What happens to an Activity's ordinary fields and to its ViewModel?

    A configuration change destroys and recreates the Activity, so ordinary fields reset. The ViewModel is retained across the change.
  2. 2. Why should network calls not run on Android's main thread?

    The UI thread must stay responsive. Use coroutines on a background dispatcher and update the UI on the main thread.
  3. 3. In Swift, two class instances each hold a strong reference to the other. What happens when your own references go away?

    ARC cannot free a cycle of strong references. Make one side weak or unowned.
  4. 4. What does [weak self] in a closure capture list do?

    A weak capture avoids a retain cycle between an object and a closure it stores. Inside the closure, self is optional.
  5. 5. Which Android component is the best fit for deferrable background work that must survive app restarts, such as uploading logs?

    WorkManager schedules guaranteed, constraint-aware background work that persists across restarts. Foreground services are for work the user is actively aware of.

Summary

  • Android's Activity is destroyed and recreated on configuration changes: save small state in onSaveInstanceState, screen state in a ViewModel, real data in a database.
  • Keep slow work off the main thread (coroutines on Android, async/await or GCD on iOS) to avoid ANRs and frozen UIs.
  • Leaks come from long-lived objects holding short-lived screens (a Context, a closure, a strong back-reference).
  • Swift's ARC frees objects when the strong count reaches zero; break retain cycles with weak, unowned and capture lists.
  • Compose and SwiftUI make the UI a function of state; MVVM with repositories and dependency injection keeps both platforms testable.

Next: SQL Query Questions, where the round turns to databases.