Beginner Android interview questions

121 questions from the Beginner lessons. Open a question to see the junior, mid and senior answers. Each one links to the lesson that explains it.

Kotlin essentials

What is the difference between val and var, and between val and const val?
Junior
val cannot be reassigned after it is set, var can. const val is a constant whose value is known at compile time.
Mid
val is a read-only reference. The object behind it can still be mutable. const val must be a primitive or String, with a value known at compile time, and is declared at top level or inside an object or companion. A normal val can be computed at runtime, for example from a function call.
Senior
const val is inlined at use sites by the compiler, so it creates no getter call and can be used in annotations. A normal top-level val compiles to a static field with a getter. I prefer val everywhere, and I choose const val only for true constants such as keys and tags. I check the compiled result with the Kotlin bytecode viewer when I need proof.
Learn it: Variables, types and null safety
How does null safety work, and where can it fail?
Junior
Types are non-null by default. A type with a question mark can hold null, and the compiler forces you to check it before use.
Mid
The compiler tracks nullability and offers ?., ?:, as? and smart casts. It can fail at the edges: Java platform types, reflection-based JSON parsers, lateinit, and !!. In those places a null can enter a non-null type.
Senior
Kotlin adds null checks on non-null parameters of non-private functions, so a bad null often throws at the next function call, not where it came from. That makes the stack trace misleading. I validate at boundaries: parse DTOs with a library that fails fast, map to domain types, and declare explicit nullable types when calling Java APIs.
Learn it: Variables, types and null safety
Why does a smart cast sometimes not compile?
Junior
The compiler is not sure the value stays the same after the null check, so it will not treat it as non-null.
Mid
Smart casts need a stable value: a local val, a local var not captured and changed by a lambda, or a val property without a custom getter in the same module. A var property or an open property can change between the check and the use. The fix is to copy it into a local val.
Senior
The rule protects against data races and overridden getters. A val property from another module could later get a custom getter when that module is changed and recompiled separately, so the compiler refuses. Copying to a local val is free at runtime and documents the intent. With Kotlin 2 the K2 compiler smart casts in a few more cases, for example after is checks joined with a logical or it casts to the closest common supertype, but it still does not smart cast var properties.
Learn it: Variables, types and null safety
When would you use lazy and when lateinit?
Junior
lateinit is for a variable set later. lazy is for a value that is computed the first time it is used.
Mid
lazy is a val with a block that runs once and is thread-safe by default. lateinit is a var that something else must set before reading, such as dependency injection. lateinit cannot be used for primitives and throws if read too early.
Senior
lazy has a synchronization cost by default. For main-thread-only values I can pass LazyThreadSafetyMode.NONE to avoid it, but only if I am certain about thread confinement. For lateinit I prefer constructor injection so the compiler enforces order. I accept lateinit only where the framework owns the timing, and I can test it with isInitialized in rare cleanup code.
Learn it: Variables, types and null safety
What is a higher-order function, and what is a closure?
Junior
A higher-order function takes a function as a parameter or returns one. A closure is a lambda that can use variables from the place where it was written.
Mid
Kotlin has function types such as (Int) -> String, so functions are values. A lambda is a closure: it captures variables from its scope, including vars, and can change them. The standard library uses this everywhere, for example map, filter and repeat.
Senior
On the JVM a capturing lambda is an object that stores the captured values. A captured var is wrapped in a Ref object so both sides share it. That costs allocations in hot paths and can leak the captured objects, so I watch what a lambda captures when it outlives the screen. For hot paths I make the higher-order function inline, which removes the object, and I verify with the bytecode viewer or a profiler.
Learn it: Functions and lambdas
What does return do inside a lambda?
Junior
A plain return inside a lambda does not return a value from the lambda. To leave only the lambda you use a label, such as return@forEach. The lambda's result is its last expression.
Mid
If the lambda is passed to an inline function, a bare return is a non-local return and leaves the enclosing function. With a label, return@forEach only ends the current lambda call, which acts like continue. In a non-inline lambda a bare return is a compile error.
Senior
Non-local return works only because inline copies the lambda body into the caller, so the return is a normal return of the caller. That is why crossinline exists: if the lambda is called from another object or thread context, a return from the outer function is impossible, so the compiler forbids it. I treat bare returns in forEach as a code smell and prefer for loops or filtering, because the intent is clearer to readers.
Learn it: Functions and lambdas
Explain inline, noinline and crossinline.
Junior
inline copies the function and its lambda into the place where it is called. noinline and crossinline are used on lambda parameters of an inline function.
Mid
inline removes the cost of creating a lambda object and calling it, and allows non-local return and reified type parameters. noinline marks a lambda parameter that must stay a real object, for example to store it or pass it to a non-inline function. crossinline keeps the lambda inlined but forbids non-local return, which is needed when it runs inside another object.
Senior
The trade-off is code size: the body is duplicated at every call site, so inlining a large function with many callers grows the app. The gain is mostly for small functions that take lambdas in hot paths. A public inline function can only use public API unless I add the PublishedApi annotation, and its body becomes part of the binary contract with callers. I measure before and after rather than inlining by habit.
Learn it: Functions and lambdas
How do default arguments work, and what can go wrong?
Junior
If you leave out an argument, Kotlin uses the default value. You can also pass arguments by name.
Mid
Defaults are evaluated on each call, so they can be expressions. Named arguments make calls readable. Java callers cannot use defaults unless the function has the JvmOverloads annotation, which generates overloads.
Senior
The compiler generates a synthetic method that takes a bitmask of which arguments were missing and fills the defaults. In a library, adding a new parameter with a default still changes the method signature, so code compiled against the old version fails at runtime with NoSuchMethodError unless I keep the old signature as an overload. For public APIs I add overloads deliberately, and I avoid long lists of defaulted booleans in favour of a small config class.
Learn it: Functions and lambdas
What is the difference between a class and a data class?
Junior
A class is a general template for objects, while a data class is specifically designed to hold data and automatically provides functions like equals and hashCode.
Mid
A data class automatically generates equals, hashCode, toString, copy and componentN functions from the properties in the primary constructor. A regular class inherits equals and hashCode from Any, which compare references.
Senior
Only primary constructor properties take part in the generated functions, so a property in the body is ignored by equals and copy. copy is shallow, and componentN is positional, so reordering constructor parameters silently changes what destructuring returns. Data classes cannot be open, abstract, sealed or inner, because a subclass would break the generated equals and copy contract. In a public library API, adding a constructor parameter changes copy and componentN, which is a binary-incompatible change, so library authors often avoid data classes in public APIs.
Learn it: Classes, objects and data classes
What is a singleton in Kotlin?
Junior
A singleton is a class that has only one instance, created using the object keyword.
Mid
An object declaration creates a singleton. On the JVM it is initialized the first time it is accessed, and that initialization is thread-safe. Its mutable state is not automatically thread-safe.
Senior
object declarations are convenient, but they hold global state for the life of the process. That makes unit tests order-dependent and can leak memory if the object keeps a Context or a View. In larger apps I let the DI framework provide a single instance per scope instead, so it can be replaced with a fake in tests.
Learn it: Classes, objects and data classes
How does the copy() function work in a data class?
Junior
It creates a new instance of the class with the same values as the original.
Mid
It creates a new instance by copying all primary constructor properties from the existing instance, and lets you override specific properties with named arguments.
Senior
copy is a shallow copy. If the data class contains a mutable object such as a MutableList, both instances share it, so mutating it through one instance changes the other. For UI state I keep properties immutable, using List instead of MutableList, so copy is enough. Also, copy calls the primary constructor, so init block validation runs again, while body properties are reinitialized rather than copied.
Learn it: Classes, objects and data classes
What is a companion object?
Junior
It is an object inside a class that allows you to call methods without creating an instance of the class.
Mid
It is a singleton instance tied to the class scope, used to hold static-like members such as factory methods or constants.
Senior
A companion object is a real object: it can implement interfaces and have extension functions, which Java statics cannot. On the JVM it is initialized when the containing class is loaded, like a Java static initializer. From Java its members are reached through Companion unless they are const, @JvmStatic or @JvmField. A common use is a factory function with a private constructor, so the class controls how instances are created.
Learn it: Classes, objects and data classes
What is the difference between a sealed class and an enum in Kotlin?
Junior
An enum is a fixed set of constants. A sealed class can have sub-types that carry different data and can be classes or objects. Both give you exhaustive when checks.
Mid
Every enum constant is a single instance of the same type with the same properties. A sealed class or sealed interface lets each sub-type have its own properties, and class sub-types can have many instances. Direct sealed sub-types must be in the same module and package. An enum compiles to a class extending java.lang.Enum; a sealed class compiles to an abstract class with a non-public constructor.
Senior
Enums give you things sealed types do not: name, ordinal, entries, valueOf, and efficient EnumSet and EnumMap, which suit fixed options that are stored or sent by name. Sealed types suit states and results where each case carries different data. In both cases, adding a case breaks every exhaustive when in client code, so in a published library that is a source-breaking change. And a client compiled against the old version gets NoWhenBranchMatchedException at runtime if the new case reaches its when.
Learn it: Sealed classes, enums and when
Why is a when expression over a sealed type exhaustive without an else branch?
Junior
The compiler knows all sub-types of a sealed type, so it checks that every sub-type has a branch. If one is missing, the code does not compile.
Mid
Direct sub-types can only be declared in the same module and package, so when the compiler builds that module it sees the complete list. It checks that each direct sub-type is covered, either by its own branch or by a branch for a nested sealed parent. Adding a new sub-type breaks every when over the parent that has no else.
Senior
Exhaustiveness is a compile-time check. The compiler still adds a hidden fallback that throws NoWhenBranchMatchedException, because the code can meet a case it did not know about when it was compiled, such as an app compiled against an older library version. An open sub-type does not break exhaustiveness: a branch is SomeOpenSub covers all of its subclasses. The real hole is an else branch, which is why I avoid else on sealed subjects.
Learn it: Sealed classes, enums and when
When would you choose a sealed interface over a sealed class?
Junior
Use a sealed interface when sub-types need to extend some other class. A class can only extend one class, so a sealed class would use up that slot.
Mid
A sealed interface lets a sub-type extend another class and implement several sealed interfaces at once. A sealed class can have a constructor and hold shared state, which an interface cannot. Choose the interface when you do not need shared state, and the class when every case shares some properties.
Senior
A sealed interface lets one type sit in two hierarchies: for example, a NetworkError can be both a DomainError and a Retryable case, and each when over either parent stays exhaustive. It also keeps data classes free to extend a base class if needed. I use a sealed class when every case must carry a common property set by the constructor, such as an id. Both have the same exhaustiveness rules and the same module-and-package restriction.
Learn it: Sealed classes, enums and when
What happens if you add a new sub-type to a sealed hierarchy and forget to update a when?
Junior
If the when has no else, the code does not compile. The compiler forces you to add a branch for the new sub-type.
Mid
Since Kotlin 1.7 this applies to both when expressions and when statements over a sealed subject. The only way the new sub-type goes unhandled is an else branch, which silently catches it. That is why else on a sealed when is dangerous.
Senior
Within one build, the compiler catches it. Across a binary boundary, it cannot: if a library adds a sub-type and an app compiled against the old version receives it, the hidden fallback throws NoWhenBranchMatchedException at runtime. So for sealed types in a public library API, adding a case is a breaking change. I document it in the release notes, or give the hierarchy an explicit Unknown case from the start if it must grow.
Learn it: Sealed classes, enums and when
What is the difference between List and MutableList?
Junior
List can only be read. MutableList can also add and remove items.
Mid
List is a read-only interface. It has no add or remove, but it is not immutable: if another reference points to the same MutableList, the List changes too. To get a stable snapshot you copy with toList.
Senior
Kotlin read-only collections are compile-time interfaces over the usual java.util classes, so there is no runtime protection. On the JVM a cast to MutableList always succeeds, because both are java.util.List, and add then works or throws UnsupportedOperationException depending on the implementation. So I do not rely on read-only for thread safety. For state shared between threads I publish immutable snapshots, for example a StateFlow holding a new list for each change, and I keep the mutable list private to one owner.
Learn it: Collections and sequences
When would you use a Sequence instead of a List?
Junior
When the list is big and I do many steps. A sequence works lazily, so it does not build a new list at every step.
Mid
A sequence processes one element through the whole chain and only runs when a terminal call is made. It helps with large data and chains that can stop early, such as filter then first or take. For small lists a normal collection is simpler and often faster.
Senior
Collection operators like map and filter are inline, so there are no lambda objects, but each step allocates an intermediate list. Sequence operators are not inline, so they allocate lambdas and iterators, and they win only when they avoid work: large inputs, several steps, or early exit. Stateful steps like sorted break the early exit, because they buffer everything. I decide with a benchmark on realistic data, not by habit, and for database-backed data I push the filtering and sorting into the query.
Learn it: Collections and sequences
What happens if you remove items from a list while looping over it?
Junior
It can crash with ConcurrentModificationException.
Mid
The iterator checks a modification counter on each step. If the list was changed outside the iterator, it throws. Use removeAll with a condition, or filter into a new list.
Senior
It is a fail-fast check, not a guarantee, so some cases, such as removing the second-to-last item, do not throw and hide the bug. The same exception appears when another thread changes the list. The fix is ownership, not a lock around the loop: one writer, readers get immutable snapshots. To catch the threading case I add a stress test that mutates from a second thread and repeats many times, because a race does not show up on every run.
Learn it: Collections and sequences
What does groupBy return and how is it different from associateBy?
Junior
groupBy returns a map from key to a list of items. associateBy returns a map from key to a single item.
Mid
groupBy keeps every item for a key in a list. associateBy keeps one item per key, and when two items share a key the last one wins, so data can be lost silently. associate lets you build both key and value.
Senior
I use associateBy only when the key is unique by contract, such as a database id, and I check that assumption, because a duplicate overwrites without a warning. For lookups in a hot path I build the map once and reuse it instead of calling find in a loop, which turns a quadratic cost into a linear one.
Learn it: Collections and sequences
What is the difference between apply and also?
Junior
Both return the object they are called on, not the lambda result. apply passes the object as this, so you can use its members directly. also passes the object as the it parameter, so you write it.member.
Mid
Both are inline extension functions on a generic T. apply takes a lambda with receiver, T.() -> Unit, so this is the object. also takes a normal lambda, (T) -> Unit, so the object is the parameter it and this still means the outer class. apply is used for configuring an object, also for side-effects like logging where the pipeline type must not change.
Senior
Because both are inline, nothing of them remains in the bytecode: the block is copied into the caller, which I can confirm in the Kotlin bytecode viewer. The difference is only name resolution at compile time. Inside apply, unqualified names resolve to the object first, which can silently hide a property of the outer class with the same name. also avoids that because this keeps meaning the outer class. I choose apply for short builder-style configuration and also when the block mainly talks to the surrounding class.
Learn it: Scope functions
When should you NOT use a scope function?
Junior
When the lambda body is long or does several unrelated things. Then a local variable and plain statements are easier to read.
Mid
Avoid using let or run only to skip a val declaration, and avoid chaining more than two scope calls, because each level adds an implicit this or it the reader must track. A common pitfall is x?.let { } ?: fallback where the lambda can return null, because the fallback then also runs for a non-null x.
Senior
I ask what the expression returns and whether the reader can see it. Swapping apply for run or let changes the result type, which is only caught by the compiler if the function declares its return type, so I declare return types on public functions and use explicit API mode in libraries. I also avoid nested receivers, because with two this objects in scope a call can silently resolve to the wrong one. When in doubt, plain if/else and named vals are easier to review.
Learn it: Scope functions
Explain the null-check idiom with let. What happens at the bytecode level?
Junior
x?.let { transform(it) } ?: fallback calls transform only when x is not null. If x is null, the let is skipped and fallback is used. It replaces a longer if (x != null) block.
Mid
The safe call checks x for null and only then runs let. let is inline, so no lambda object is created. The elvis operator uses the fallback whenever the left side is null. The pitfall is that the left side is the let result, so if the lambda returns null the fallback runs too, even though x was not null.
Senior
Because let is inline, the compiled code is just a null check on x with a branch: the lambda body is copied into the caller and the elvis becomes another null check on the result, with no lambda class and no invoke call. I confirm it with the Kotlin bytecode viewer and decompiler. The fallback is evaluated only when needed, not eagerly. When the lambda can return null I use if/else instead, because the elvis cannot tell the two null cases apart.
Learn it: Scope functions
A colleague wrote val config = builder.apply { setup(); true }. Is this correct?
Junior
No. apply returns the object it was called on (the builder), not the true from the lambda. So config is the builder, not a Boolean. The true is ignored.
Mid
apply is declared as inline fun <T> T.apply(block: T.() -> Unit): T, so it always returns T, the object. The lambda's expected type is Unit, so its last expression true is simply discarded. Use run if you need the lambda's value, or remove the true if it was a mistake.
Senior
The code compiles, which is the danger: nothing warns that true is ignored. It usually means the author wanted both a configured object and a success flag. I would split that: apply for configuration, and a separate return value such as a Result or a sealed type for success. Writing the expected type, val config: Builder or val ok: Boolean, makes the compiler catch the mismatch at the declaration.
Learn it: Scope functions
How does the compiler resolve an extension function call?
Junior
The compiler looks at the type of the receiver and finds a matching extension function. It then rewrites the call as a static function with the receiver as the first argument.
Mid
Resolution is static: the compiler uses the declared type at the call site, not the runtime type. The call s.ext() where s is declared as Base always picks Base.ext(), even if the runtime object is a Sub. The generated bytecode is a static method in a file-level class like MyFileKt.
Senior
I can confirm it in the Kotlin bytecode viewer: the call is an invokestatic on MyFileKt.ext(receiver), with no virtual dispatch. Members are tried before extensions, and among extensions the closest scope wins, so an explicit import beats a default stdlib import. The classic bug is overloading an extension for a subtype, such as Throwable and HttpException, while callers hold the base type: the base version is always chosen. When behaviour must depend on the runtime type, I use a member, or one extension that branches with when on the runtime type.
Learn it: Extension functions and properties
Can an extension function access private members of the class it extends?
Junior
No. An extension function can only use members it could use from outside the class. Private members are not visible.
Mid
The extension is compiled as a static function outside the class, so it gets normal visibility rules: no private or protected members, but internal members are visible if the extension is in the same module. If you need private state, add a member function.
Senior
Extensions do not break encapsulation, because they only see what any outside code in the same place could see. The exception is an extension declared inside the class as a member extension, which can use the class's private members because it is part of the class body. Since extensions only see the public API, they are a good fit for helpers in other modules, for example core-ktx adding View.isVisible without touching View.
Learn it: Extension functions and properties
What happens when a member and an extension have the same signature?
Junior
The member function is called. The extension is ignored for that call.
Mid
The member always shadows an extension with the same name and applicable parameters. This applies to functions and properties. The compiler gives a warning that the extension is shadowed by a member, but it still compiles. An extension with the same name and different parameter types is just an overload and can be called.
Senior
Members win because overload resolution looks at members of the receiver before extensions. This matters when a library later adds a member with the same name as your extension: after the upgrade, your extension silently stops being called, and the only signal is a new compiler warning. I treat that warning as an error in CI and rename extensions that collide with members.
Learn it: Extension functions and properties
Can an extension property have a backing field?
Junior
No. An extension property must have an explicit getter, and a setter if it is a var. It cannot have an initializer like = 0.
Mid
An extension does not add anything to the class, so there is no place to store a value per instance. The property compiles to a static getter method that takes the receiver as a parameter, and field is not available inside it. It can only compute its value from the receiver.
Senior
If a team needs per-instance state, the right answer is a member property. A top-level variable behind the getter is one value shared by every instance, which causes bugs that only show up with two instances. A WeakHashMap keyed by the receiver works but needs care with thread safety and identity. For views, the setTag API exists for this. In the bytecode viewer a computed extension property is just a static getX(receiver) method with no field.
Learn it: Extension functions and properties
What is the difference between covariant and contravariant generics in Kotlin?
Junior
Covariant means out T, and a subtype like List<String> can be used where List<Any> is expected. Contravariant means in T, and a supertype like Consumer<Any> can be used where Consumer<String> is expected. Invariant means no substitution is allowed, like MutableList.
Mid
Covariance (out) applies when T appears only in output positions, so the type is a producer. Contravariance (in) applies when T appears only in input positions, so the type is a consumer. The compiler enforces this on non-private members: an out T cannot be a parameter type and an in T cannot be a return type. MutableList is invariant because it has both get() and add().
Senior
Kotlin has declaration-site variance, written once on the type, and use-site variance, like Java wildcards: Comparator<in T> in sortedWith, or Array<out Any> for a read-only array parameter. Variance is purely a compile-time check; after erasure there is nothing left of it at runtime. Sometimes a covariant type needs T in an input position that is actually safe, like List.contains(element), and the stdlib marks it @UnsafeVariance. For Java callers, Kotlin turns declaration-site variance into wildcards such as List<? extends T> in parameters, which @JvmSuppressWildcards can turn off.
Learn it: Generics and variance basics
What is star projection and when do you use it?
Junior
Star projection is written Foo<*>. It means you do not know the type argument. For MutableList<*> you can read elements as Any? but you cannot add anything.
Mid
For a covariant or invariant type, reading through Foo<*> gives the upper bound, usually Any?. Writing is not allowed, because the compiler does not know which type is safe. You use it when the code does not care about the element type, such as a function that prints the size of any list, or in type checks like x is List<*>, because x is List<String> cannot be checked at runtime.
Senior
Star projection plays the role of Java's List<?> wildcard. Formally, for Foo<T> it means Foo<out Any?> when reading and Foo<in Nothing> when writing. So for a contravariant Consumer<*> you can call nothing that takes T. I use it at type-check and reflection boundaries, then turn it into a known type with filterIsInstance or a reified helper instead of an unchecked cast.
Learn it: Generics and variance basics
What is type erasure and how does reified help?
Junior
Type erasure means that at runtime, List<String> and List<Int> are the same thing: java.util.List. The type argument is removed. Reified, on an inline function, makes the real type available so you can use is T inside the function.
Mid
The compiler checks generic types and then erases them in the bytecode, inserting casts where values are read. So is T on a normal type parameter does not compile. With inline and reified, the compiler copies the function body into each call site and replaces T with the real type, so is T and T::class work. That only works because the function is inlined; a normal function has one compiled body for all T.
Senior
The object carries no type argument, but declarations do: the class file keeps generic signatures for fields, methods and supertypes, which is why Gson's TypeToken works through an anonymous subclass. reified functions cannot be called from Java and add bytecode at every call site, so for public APIs used from Java I offer an overload that takes a Class or KClass, and keep the reified version as a thin inline wrapper over it.
Learn it: Generics and variance basics
Why is MutableList<T> invariant?
Junior
MutableList<T> is invariant because it has both get() which returns T and add() which takes T. It cannot be covariant or contravariant. So MutableList<String> is not a subtype of MutableList<Any>.
Mid
If MutableList were covariant, you could assign a MutableList<String> to a MutableList<Any> variable, then add an Int, corrupting the original list. If it were contravariant, you could read a non-String value from a MutableList<String>. Invariance prevents both. The stdlib splits the read-only List<out E> from MutableList<E> so read-only APIs can be covariant.
Senior
Java arrays show the cost of getting this wrong: they are covariant, so Object[] objs = new String[1]; objs[0] = 1 compiles and throws ArrayStoreException at runtime. Kotlin's Array<T> is invariant to avoid that. In APIs I expose List<T> or Flow<T> and keep MutableList or MutableStateFlow private, so callers get covariance and cannot mutate my state. When a function only reads, I take List<out T> or Array<out T> so callers can pass subtypes.
Learn it: Generics and variance basics

Tooling

What is the difference between the root build.gradle.kts and the app build.gradle.kts?
Junior
The root file is for the whole project and the app file is for the app module. Dependencies and Android settings are written in the app file.
Mid
The root build file declares plugins that modules reuse, usually with apply false, so versions are set once. The module file applies the plugins and holds the android block, such as namespace, compileSdk and build types, and its dependencies. Each module has its own build file.
Senior
Modules are the unit of configuration and caching. The root build file should stay almost empty, and shared logic belongs in convention plugins in a build-logic included build so modules do not copy blocks. This keeps configuration consistent and helps incremental builds, because Gradle can skip unchanged modules. I check module boundaries with the dependency graph, not by folder names.
Learn it: Android Studio project structure
What is a source set?
Junior
A folder with code and resources for part of the build. main is shared by all builds, and debug or release add extra files.
Mid
Each variant combines main with the source sets of its build type and flavors. Code and resources from those folders are merged. Resources with the same name override main, but a class defined in two source sets of one variant is a duplicate class error.
Senior
Source sets are how variants differ without if statements: a debug folder can hold a debug menu or a fake, and release can hold nothing. The rule I enforce is that main must compile alone, and variant folders provide implementations of types declared in main. I verify by compiling every variant in CI, because the IDE only checks the selected one.
Learn it: Android Studio project structure
Why must the Gradle wrapper be committed?
Junior
So everyone builds with the same Gradle version without installing it by hand.
Mid
gradlew reads gradle-wrapper.properties, downloads the pinned Gradle distribution and runs it. This makes builds repeatable across laptops and CI. Android Gradle Plugin versions only work with some Gradle versions, so a mismatch gives confusing errors.
Senior
Pinning the distribution is part of build reproducibility. I also use the distributionSha256Sum property so a tampered download fails, and I upgrade Gradle and AGP together using the compatibility table in the official docs. On CI I run ./gradlew only, so the build never depends on a preinstalled version.
Learn it: Android Studio project structure
What is the difference between compileSdk, targetSdk and minSdk?
Junior
minSdk is the oldest Android version that can install the app. targetSdk is the version the app was tested for. compileSdk is the version used to compile the code.
Mid
compileSdk decides which APIs you can reference. minSdk filters devices, and calling newer APIs below it needs a version check. targetSdk opts the app into the behavior changes of that Android version, such as new permission rules, and Google Play requires new apps and updates to target a recent level.
Senior
I raise compileSdk first because it is safe and shows deprecations early. Then I read the behavior-changes page for the new targetSdk, test the affected flows such as background work, notifications and storage, and raise targetSdk last, behind a release train. I use lint with NewApi checks to protect the minSdk boundary.
Learn it: Gradle basics and build variants
What is a build variant?
Junior
A build made from one build type and one product flavor, such as freeDebug.
Mid
Variants are the product of build types and flavors across all flavor dimensions. Each has its own source sets, manifest, resources and dependencies, and its own Gradle tasks such as assembleFreeDebug.
Senior
Variants multiply, so each new flavor dimension multiplies CI work and configuration time. I keep dimensions few, use build types for environment, and use runtime config or feature flags for what does not need a separate binary. I disable variants I never ship with androidComponents.beforeVariants, so the build stays fast.
Learn it: Gradle basics and build variants
implementation or api?
Junior
implementation hides the dependency from other modules. api shares it.
Mid
With implementation, a change in the dependency recompiles only this module. With api it also recompiles every consumer, and consumers can use its types. Use api only when the dependency types appear in your public API.
Senior
implementation keeps the compile classpath small and gives better incremental builds and clearer boundaries. I verify with the dependencies task and by checking that public signatures do not expose types from an implementation dependency. In a multi-module app, a wrong api often shows up as a slow build after one small change in a core module.
Learn it: Gradle basics and build variants
A release build crashes but debug works. How do you investigate?
Junior
Check the logs and compare the builds. Release uses minification, so something may have been removed or renamed.
Mid
I reproduce on a local release-like build, restore the stack trace with the R8 mapping file, and look for reflection, serialization or code loaded by name. Then I add keep rules or switch to codegen based libraries.
Senior
I diff behavior, not only code: minification, resource shrinking, signing and the release-only source set. With -printconfiguration and -printusage, R8 writes the merged keep rules and a list of removed code, so I can see what was stripped. I add a minified build to CI instrumented tests so this class of bug fails before it ships.
Learn it: Gradle basics and build variants
What are the four app components and how are they declared in the manifest?
Junior
The four components are Activity, Service, BroadcastReceiver, and ContentProvider. Each is declared as a child element inside the application tag in AndroidManifest.xml, with an android:name attribute pointing to the class.
Mid
Beyond the basic declaration, a component can carry intent filters that define which implicit intents it handles, and an android:exported flag that controls cross-app access. Receivers are the only component that can also be registered at runtime with registerReceiver. The manifest merger combines declarations from all libraries into one final manifest, so your APK contains components you did not write.
Senior
Each component is an entry point the system can start on its own, possibly in a fresh process, which is why they must be declared up front. A Compose app may have a single Activity but still ship services, receivers and providers, many of them from libraries, for example the startup provider that initializes WorkManager. I review the Merged Manifest after dependency updates, keep exported components to a minimum, and protect the ones that must be exported with permissions or caller checks.
Learn it: The manifest and app components
How does manifest merging work between app and library modules?
Junior
When you add a library, its AndroidManifest.xml is combined with the app's manifest at build time. You can use tools: attributes such as tools:node and tools:replace to control the result.
Mid
Manifests have a priority: build variant source sets first, then the app's main manifest, then libraries in the order of the dependencies block. Lower-priority manifests are merged into higher-priority ones. If two manifests set the same attribute to different values, the build fails until you add tools:replace for that attribute. tools:node="remove" drops an element and tools:node="replace" swaps it entirely. Removing a component the library still uses causes a runtime crash.
Senior
The merger runs as part of the AGP build for each variant. The Merged Manifest view in Android Studio and the build/outputs/logs/manifest-merger-<variant>-report.txt log show which file contributed each element and how conflicts were resolved. Libraries also add permissions, so I check the merged uses-permission list as well, and use tools:node="remove" for a permission the app should not request. In CI you can diff the merged manifest against a known-good baseline to catch new exported components or permissions.
Learn it: The manifest and app components
What is android:exported and why was it made mandatory on Android 12?
Junior
android:exported controls whether other apps on the device can start or bind to a component. When you target Android 12 or higher, it must be set explicitly for any component that has an intent filter. Before that, such components were exported by default.
Mid
The old default was exported="true" whenever a component had an intent filter, so many components were exposed by accident. Making it explicit forces a conscious choice. Without an intent filter the default is false. A common surprise is a library that has not updated its manifest, which breaks your build after a targetSdk bump; you update the library or redeclare the component in your app manifest with the attribute.
Senior
It is security hardening: an exported component is part of the app's attack surface, and its extras are untrusted input. I audit every exported component in the merged manifest, not just my own code. For components that must be exported, such as a deep-link Activity, I validate every input and protect sensitive ones with a signature permission. I can verify the result on a device with adb shell dumpsys package and the package name.
Learn it: The manifest and app components
How do intent filters route intents to components?
Junior
An intent filter inside a component declares which actions, categories, and data it handles. The system compares an implicit intent with these filters to find matching components. A launcher activity needs the MAIN action and the LAUNCHER category.
Mid
To pass, the intent's action must be one of the filter's actions, every category in the intent must be listed in the filter, and the intent's data and MIME type must match the filter's data elements. startActivity adds CATEGORY_DEFAULT to implicit intents, so an activity filter without the DEFAULT category never receives them. You can test with adb shell am start -a android.intent.action.VIEW -d https://example.com.
Senior
Explicit intents skip filter matching entirely; filters only apply to implicit intents. Since Android 11, another app's components are only visible to your queries if you declare them in a queries element, so resolveActivity or queryIntentActivities can return nothing even though the app is installed. Since Android 13, when an external app sends an explicit intent to your exported component, it is only delivered if it matches one of that component's filters when you target 33+. For links, I verify App Links with assetlinks.json so the app opens instead of a chooser.
Learn it: The manifest and app components
How does Android decide which resource value to use at runtime?
Junior
Android looks at the device configuration, such as language, screen size and dark mode, and picks the folder in res/ whose qualifiers match. If nothing qualified matches, it uses the default folder such as values/.
Mid
It works per resource. First it drops every folder whose qualifiers contradict the device. Then it walks the qualifiers in their fixed precedence order (language, then smallest width, available width, orientation, night mode, density and so on), and at each step, if any remaining folder has that qualifier, it keeps only those. The last one left wins. So values-fr beats values-night on a French device in dark mode.
Senior
Density is the exception: Android picks the closest density and scales instead of eliminating. The selection is per resource and is redone after a configuration change, which by default recreates the Activity. Resources from libraries are merged with the app's, and the app's value wins for the same name, so libraries should prefix their names. To debug, I check the device configuration (adb shell dumpsys activity, or the Layout Inspector's resolved attribute values) and the merged resources, then apply the elimination steps by hand.
Learn it: Resources, qualifiers and themes
What is the difference between a Style and a Theme?
Junior
A style is a reusable set of attributes for one view. A theme is applied to the Application, an Activity or a part of the view tree and sets global attributes like colours and the window background.
Mid
Both are style resources; the difference is how they are applied. A style set with style= only affects that one view and is not inherited by its children. A theme set with android:theme, in the manifest or on a view, becomes part of the Context, so every view below can read its attributes with ?attr/colorPrimary. A theme overlay changes only a few attributes for a subtree.
Senior
Attribute values are resolved in order: attributes set directly on the view, then its style, then the default style the widget looks up from the theme, then the theme. Good design puts colours and typography in the theme and component looks in default styles set by the theme, so screens rarely need inline attributes. setTheme must be called before views are inflated, so switching themes at runtime usually means recreating the Activity. In Compose, MaterialTheme provides the same values through CompositionLocals instead of XML attributes.
Learn it: Resources, qualifiers and themes
How do you support dark mode without writing any Kotlin code?
Junior
Use a DayNight parent theme and create a values-night/ folder with night versions of your theme or colours. The system picks them when the user turns on dark mode.
Mid
Use a DayNight parent such as Theme.Material3.DayNight.NoActionBar and override the colour values in values-night/. When the user switches, the uiMode configuration changes, and by default the Activity is recreated and picks the night resources. Views should use theme attributes like ?attr/colorOnSurface instead of hard-coded colours.
Senior
The -night qualifier works on any resource type, for example values-night/colors.xml or drawable-night/. For an in-app setting I use AppCompatDelegate.setDefaultNightMode, which recreates activities as needed. If an Activity declares configChanges="uiMode" it is not recreated and must update itself in onConfigurationChanged. Compose apps usually choose the colour scheme in code with isSystemInDarkTheme, so the XML theme mainly matters for the window background and splash. I check both modes with screenshot tests on several screen sizes.
Learn it: Resources, qualifiers and themes
A user reports that a string shows '1 items' instead of '1 item'. What do you check?
Junior
Check that the string is a plurals resource with both quantity=one and quantity=other, and that the code calls getQuantityString instead of getString.
Mid
Most likely the code uses getString or a formatted string resource, which never applies plural rules. Use getQuantityString(R.plurals.items, count, count): the first count picks the form, the second fills the placeholder. Also check that the right count is passed as the quantity.
Senior
Then I check the translations: each language needs its own plural forms, which lint's MissingQuantity reports. quantity="zero" is only used by languages whose grammar has a zero form, so English never selects it; a special 'No items' text needs a separate string and an if in code. In Compose, pluralStringResource does the same job. For a library that defines the plural, I check whether the app overrides it with the same name.
Learn it: Resources, qualifiers and themes
How do you narrow down a Logcat flood to find the relevant log line?
Junior
I filter to my app with package:mine in the Logcat window and set the level to WARN or ERROR to hide debug noise. Then I add a tag filter for the part of the app I care about.
Mid
I clear the buffers with adb logcat -c, reproduce the bug, then filter by package or PID and tag. If I do not know the tag, I search the message text, or the codebase for the log call. For a crash I look for FATAL EXCEPTION, which is in the crash buffer, and for an ANR I look at ActivityManager lines in the system buffer.
Senior
I combine package, tag and level in Android Studio's query syntax, and use regex on the message when the tag is noisy. If I need a value without stopping the app, I use a logging breakpoint instead of adding a Log call and rebuilding. For a bug from QA I ask for a bug report with adb bugreport, which contains all buffers plus ANR traces and system state. Production is different: logs never leave the device, so I rely on the crash reporter with uploaded mapping files and on Android vitals.
Learn it: Logcat and the debugger
What is a conditional breakpoint and when would you use one?
Junior
It is a breakpoint that only pauses when a condition is true. You set it by right-clicking the breakpoint dot and typing an expression.
Mid
You use it when a code path runs thousands of times but the bug only triggers for one specific input. For example, a loop that processes many items but crashes on a specific index. The condition avoids stepping through the other iterations. Keep the expression cheap, because it runs on every hit.
Senior
Beyond the loop case, I use conditions to stop on a bad state, for example state is Loading && retryCount > 3, or on a position that should never be bound. With Suspend unchecked and an expression to log, the same breakpoint becomes a logging breakpoint. When a value changes and I cannot find the writer, I use a field watchpoint. All of these slow the app because the debugger evaluates them on every hit, so I remove them before measuring performance.
Learn it: Logcat and the debugger
A crash only happens on a user's device. How do you diagnose it?
Junior
I look for a matching stack trace in the crash dashboard and ask the user which steps led to the crash.
Mid
I check the crash reporter and Play Console's Android vitals for the stack trace, device model and Android version. I make sure the R8 mapping file for that build is uploaded so the stack trace is readable. Then I try to reproduce on an emulator or device with the same Android version, and read Logcat there.
Senior
First I check that the crash is actually being reported: a third-party handler that does not forward, a native crash without NDK symbols, or an ANR the SDK does not capture can all hide it. On Android 11+ I can call ActivityManager.getHistoricalProcessExitReasons on the next launch to learn why the process ended, crash, ANR or low memory, and send that to analytics. I reproduce by matching Android version, locale and network conditions. The fix is not just the null check; it is also making that class of failure visible in the dashboard.
Learn it: Logcat and the debugger
What are the different logcat buffers and what goes in each?
Junior
There is a main buffer for app logs and a crash buffer for fatal exceptions. You can read one with adb logcat -b main or -b crash.
Mid
main holds app logs, system holds logs from system services such as ActivityManager, crash holds fatal exception stack traces, events holds binary system events, and radio holds telephony logs. adb logcat shows main, system and crash by default.
Senior
Each buffer is a separate fixed-size ring in memory, managed by logd, so a busy device overwrites old lines quickly and everything is gone after a reboot. The crash buffer stays useful longer because only crashes go there. I check and change sizes with adb logcat -g and -G, or in Developer options under Logger buffer sizes. On a test device farm I dump the buffers right after each failed test with adb logcat -d, or capture a full bug report, so the evidence is saved before it is overwritten.
Learn it: Logcat and the debugger

App fundamentals

What happens when the user rotates the screen?
Junior
The Activity is destroyed and created again. onCreate runs a second time, so anything kept only in the Activity's fields is lost unless it was saved.
Mid
It is a configuration change, so the system destroys and recreates the Activity: onPause, onStop, onSaveInstanceState, onDestroy, then onCreate with the saved Bundle, onStart, onRestoreInstanceState, onResume. A ViewModel survives because it is retained across the recreation. Small UI state goes in rememberSaveable or SavedStateHandle.
Senior
Rotation is one of many configuration changes, and it is the easy case because the ViewModel survives. I design for process death instead: screen state that must survive goes in SavedStateHandle and stays small, heavy data is reloaded from the data layer, and long drafts go to disk. I verify with Don't keep activities and by killing the process, and I keep a state restoration test so it does not regress.
Learn it: Activity lifecycle and configuration changes
What is the difference between onPause and onStop?
Junior
onPause means the Activity is leaving the foreground but may still be partly visible. onStop means it is no longer visible at all.
Mid
onPause runs when the Activity leaves the foreground but may still be visible, for example when a translucent or dialog-themed Activity opens on top, or when it enters picture-in-picture. A normal Dialog shown by the same Activity does not pause it, and since Android 10 activities in multi-window stay resumed. onPause must be fast because the next Activity is not resumed until it returns. onStop runs when the Activity is fully hidden, and it is the right place to release heavier resources and save drafts.
Senior
With multi-window and foldables, an Activity can stay visible while paused for a long time, so UI updates and video should keep running until onStop, not onPause. Since Android 10 several visible activities can be resumed at once, so exclusive resources like the camera need onTopResumedActivityChanged or a clear ownership rule rather than assumptions about onPause.
Learn it: Activity lifecycle and configuration changes
How does a ViewModel survive a configuration change?
Junior
The system keeps the ViewModel in memory while the Activity is recreated and gives the same one to the new Activity.
Mid
ViewModels live in a ViewModelStore owned by the Activity, Fragment or navigation back stack entry. On a configuration change the store is retained and handed to the new instance. When the owner is finished for good, the store is cleared and onCleared runs.
Senior
ComponentActivity returns its ViewModelStore from onRetainNonConfigurationInstance. The framework holds that object across the relaunch and the new instance reads it back with getLastNonConfigurationInstance. A lifecycle observer on ON_DESTROY clears the store only when isChangingConfigurations is false, which is why onCleared runs just before onDestroy. It is an in-memory handoff inside one process, which is exactly why it cannot survive process death.
Learn it: Activity lifecycle and configuration changes
How do you handle process death?
Junior
Save important values so they can be restored when the app is opened again, for example with rememberSaveable.
Mid
Use SavedStateHandle in the ViewModel for small screen state, rememberSaveable for pure UI state, and a database or DataStore for anything large or important. Test it with adb shell am kill while the app is in the background.
Senior
I sort state into three groups: navigation and small UI state go to saved state, user-created data goes to disk as soon as it changes, and everything else is derived again from the data layer. I keep the saved Bundle small to avoid TransactionTooLargeException, add restoration tests for critical flows such as checkout, and watch for sessions that restart on the first screen as a signal that restoration is broken.
Learn it: Activity lifecycle and configuration changes
What is the difference between a Fragment's lifecycle and its view's lifecycle?
Junior
The Fragment can stay alive while its view is destroyed. For example, when it is on the back stack, onDestroyView runs but onDestroy does not.
Mid
A Fragment has its own lifecycle plus a separate view lifecycle exposed as viewLifecycleOwner. The view lifecycle runs from onCreateView to onDestroyView and can happen many times for one Fragment instance. Anything tied to the view, such as observers, adapters and the binding, belongs to the view lifecycle.
Senior
The split exists because of the back stack: the FragmentManager can destroy the view to save memory while keeping the instance and its state. I verify it with a log of onCreateView and onDestroyView while navigating forward and back, and with LeakCanary for leaked views. The trade-off is that bugs only show on the second visit, so I always test the forward and back loop, not just first launch.
Learn it: Fragments and their lifecycle
Why should you observe LiveData with viewLifecycleOwner?
Junior
Because the view can be recreated while the Fragment stays. Observing with the Fragment adds a new observer each time.
Mid
A LiveData observer is removed only when its owner is destroyed. The Fragment owner survives while the view is recreated, so onViewCreated registers a second observer on top of the first. viewLifecycleOwner is destroyed with the view, so observers are removed.
Senior
The same applies to Flow: launch on viewLifecycleOwner.lifecycleScope with repeatOnLifecycle so collection stops with the view. Also be careful with events: even a single observer replays the last value to a rebuilt view, so one-off events like navigation or dialogs need to be modelled as consumed state. I confirm the fix with a counter in the observer across several back-stack round trips.
Learn it: Fragments and their lifecycle
How do two Fragments communicate?
Junior
Through a shared ViewModel scoped to the Activity, or by sending a result with the Fragment Result API.
Mid
The Fragment Result API uses setFragmentResult on one side and setFragmentResultListener on the other, keyed by a request key, on the same FragmentManager. A shared ViewModel via activityViewModels or navGraphViewModels fits ongoing shared state. Interfaces on the host Activity and setTargetFragment are the old ways.
Senior
I choose by lifetime. A one-time result, like a picked date, uses the Fragment Result API because it is delivered once and survives recreation through the FragmentManager. Shared screen state uses a ViewModel scoped as narrowly as possible, ideally a navigation graph, so it is cleared when the flow ends. Scoping to the Activity is easy but keeps state alive too long.
Learn it: Fragments and their lifecycle
What is the difference between an explicit and an implicit Intent?
Junior
An explicit Intent names the target class directly, for example Intent(context, DetailActivity::class.java). An implicit Intent only describes the work, with an action and optional data, and the system finds a matching component through intent filters.
Mid
An explicit intent has a non-null ComponentName, so the system skips filter matching entirely. An implicit intent is compared with the intent filters of installed apps: the action must be in the filter, every intent category must be in the filter, and the data must match. startActivity adds CATEGORY_DEFAULT, so activity filters need it. If several activities match, the user picks one in a disambiguation dialog; if none match, startActivity throws ActivityNotFoundException.
Senior
Inside my app I use explicit intents. Between apps, implicit intents decouple the caller from the handler. Recent targets tightened both sides: from API 33, intents from other apps must match one of your exported component's filters, and from API 34, implicit intents only reach exported components and mutable PendingIntents cannot wrap implicit intents. Explicit intents to another app still need that component to be exported. I treat everything arriving through an exported component as untrusted input.
Learn it: Intents and intent filters
What changed with android:exported and package visibility?
Junior
When you target Android 12, every Activity, Service, or Receiver with an intent filter must declare android:exported explicitly. When you target Android 11, your app cannot see most other apps through PackageManager unless you declare them in a queries element.
Mid
Before API 31, a component with an intent filter was exported by default; now the build fails if exported is missing. Package visibility filters PackageManager results: queryIntentActivities, resolveActivity and getPackageInfo leave out apps you did not declare. It does not block startActivity or the system chooser. The common pitfall is raising targetSdk to 30 and finding that a custom picker or a resolveActivity check suddenly finds nothing.
Senior
I enable the QueryPermissionsNeeded lint check, and prefer narrow intent-based queries over package names or QUERY_ALL_PACKAGES, which Google Play only allows for specific use cases. Often the better fix is to remove the lookup: launch the intent and catch ActivityNotFoundException. For exported components, I audit the merged manifest so only components that really receive external intents are exported, and for App Links I verify assetlinks.json is served from /.well-known/ and that the filter uses https with autoVerify.
Learn it: Intents and intent filters
Explain the Activity Result API and why it replaced onActivityResult.
Junior
You call registerForActivityResult with a contract such as StartActivityForResult or GetContent. You get a launcher and a callback lambda that receives the result. This replaces startActivityForResult with request codes and a big onActivityResult override.
Mid
Each contract defines the input and output types, so results are type-safe and there are no request-code collisions between Activities and Fragments. The ActivityResultRegistry saves which requests are pending, so when the Activity is recreated after rotation or process death, the result is delivered to the callback registered again in the new instance. That is why registration must happen unconditionally before STARTED; registering later throws IllegalStateException.
Senior
Contracts also make results testable: you can pass a test ActivityResultRegistry and check what was launched and returned without starting another app. In Compose I use rememberLauncherForActivityResult. I keep the launcher in the UI layer; a ViewModel exposes state or an event saying a picker is needed, and the UI launches it and hands the result back. Custom contracts wrap app-specific flows so callers see typed inputs and outputs.
Learn it: Intents and intent filters
How do you open an existing screen from a notification without creating duplicates?
Junior
Use an Intent to the Activity and wrap it in a PendingIntent with FLAG_IMMUTABLE. Add flags so the existing screen is reused instead of creating a new copy.
Mid
FLAG_ACTIVITY_CLEAR_TOP plus FLAG_ACTIVITY_SINGLE_TOP: if the Activity is already in the task, everything above it is finished and the existing instance receives the new intent in onNewIntent. Without SINGLE_TOP, a standard Activity would be finished and recreated. The PendingIntent needs FLAG_IMMUTABLE when targeting API 31+, and FLAG_UPDATE_CURRENT if its extras change.
Senior
For a deep screen I build a synthetic back stack with TaskStackBuilder, or with Navigation's NavDeepLinkBuilder, so Back goes to the parent screen instead of leaving the app. In a single-Activity app the notification usually targets the one Activity with a deep link and lets Navigation handle it, and onNewIntent forwards new links when the Activity already exists. I test both paths: app killed, and app already open on another screen.
Learn it: Intents and intent filters
Walk through the runtime permission flow for a dangerous permission like CAMERA.
Junior
Declare the permission in the manifest. Check it with checkSelfPermission. If it is not granted, request it with the Activity Result API. The system shows a dialog, the user taps Allow or Deny, and you get the result in a callback.
Mid
Check ContextCompat.checkSelfPermission first. If not granted and shouldShowRequestPermissionRationale is true, show an in-app explanation and then call launcher.launch(). Otherwise launch directly. In the callback, if the result is false and shouldShowRequestPermissionRationale is now false, the user denied permanently, so you explain and offer a button to ACTION_APPLICATION_DETAILS_SETTINGS. The launcher is registered with registerForActivityResult before the activity is STARTED.
Senior
I model it as states: not asked, granted, denied, permanently denied, plus partial for photos on Android 14. The permanent case is detected right after a denial, because shouldShowRequestPermissionRationale returns false both before the first request and after a permanent denial. I wrap the check and the feature call in one class so every call site goes through the same guard, never cache 'granted' because users and auto-reset can revoke it, and re-check in onResume after sending the user to Settings. I also prefer APIs that need no permission when they fit, like the Photo Picker or an ACTION_IMAGE_CAPTURE intent.
Learn it: Runtime permissions
What does shouldShowRequestPermissionRationale return, and why is it confusing?
Junior
It returns true if the user denied the permission before but you can still ask again. It returns false if the permission is granted, was never requested, or was denied permanently.
Mid
The confusion is that false covers both 'never asked' and 'permanently denied'. The usual solution is to read it in the result callback: if the request was just denied and it returns false, the denial is permanent. Some apps also store whether they have asked before. On Android 11+, two denials count as permanent, and dismissing the dialog without choosing does not count as a denial.
Senior
The value comes from the per-permission flags the system keeps: after a normal denial it returns true; after the user chose 'don't ask again', or denied twice on Android 11+, the permission is fixed by the user and it returns false, and launch() returns false at once with no dialog. Device policy can also fix a permission. Because I cannot read those flags directly, I keep the logic in one place that combines checkSelfPermission, the rationale value after a denial and an 'asked before' flag, and I test it on real devices from several manufacturers.
Learn it: Runtime permissions
How do you handle media permissions after Android 13?
Junior
For apps targeting Android 13, READ_EXTERNAL_STORAGE no longer gives access to media on Android 13+. You request READ_MEDIA_IMAGES, READ_MEDIA_VIDEO or READ_MEDIA_AUDIO for the type you need, and keep READ_EXTERNAL_STORAGE for older versions.
Mid
I branch on Build.VERSION.SDK_INT. Images and video share one dialog when requested together, and audio has its own, so I check the result for each permission. READ_EXTERNAL_STORAGE is declared with maxSdkVersion 32. If the app only needs the user to choose a photo, I use the Photo Picker instead, which needs no permission.
Senior
On Android 14 the user can grant partial access. I declare READ_MEDIA_VISUAL_USER_SELECTED; if it is granted and READ_MEDIA_IMAGES is not, MediaStore returns only the selected items, so the UI shows them and offers 'select more', which simply requests again. If I do not declare it, the system still offers the choice in a compatibility mode with temporary access, which is harder to reason about. Access can change while the app is in the background, so I re-query MediaStore and re-check permissions in onResume rather than caching results, and I test on API 32, 33 and 34+ emulators.
Learn it: Runtime permissions
What happens if you call registerForActivityResult in onResume instead of onCreate?
Junior
It throws an IllegalStateException because the activity is already started. You should register the launcher earlier, in onCreate or as a field.
Mid
The Activity Result API requires registration before the lifecycle owner is STARTED, and the error says so. onResume runs after STARTED, so it fails every time. The reason is process death and rotation: the launcher must be registered again in the same order on every creation, early enough that a result pending from before recreation can be delivered to it.
Senior
Each registration gets a key from the ActivityResultRegistry, and pending results are kept in saved state under that key. When the activity is recreated, the field initializers run again, re-register with the same keys, and the registry delivers the stored result once the owner reaches STARTED. Registering late, or conditionally, would break that matching, so the API refuses. In Compose, rememberLauncherForActivityResult handles the key with rememberSaveable, but it must stay in composition while the request is in flight. I keep launchers as fields in Activities and Fragments and add a lint check against registration inside lifecycle callbacks.
Learn it: Runtime permissions
What is the difference between the Application Context and an Activity Context?
Junior
The Application Context lives for the whole process and is safe to keep in long-lived objects. An Activity Context lives only while the Activity is alive and should not be stored in objects that outlive it. You get the Application Context with applicationContext.
Mid
Both are Contexts, but an Activity is a ContextThemeWrapper with its own theme and window. That is why dialogs, view inflation and theme attributes need an Activity Context, and why startActivity from the Application Context needs FLAG_ACTIVITY_NEW_TASK. The Application Context is the single Application object, so storing it never leaks a screen.
Senior
Application, Activity and Service are ContextWrappers; each delegates to a ContextImpl the system creates for that component, and getApplicationContext() returns the process's Application object. The Activity's ContextImpl also carries its own Resources with the Activity's configuration, so in multi-window or after a configuration change the Activity's resources can differ from the Application's. So the rule is: keep the Application Context, use the Activity Context only for the work that needs a theme, a window or the current configuration, and check with LeakCanary in debug and UI tests.
Learn it: Context: application vs activity
When is it safe to pass an Activity Context to a ViewModel?
Junior
It is not safe to store an Activity Context in a ViewModel, because the ViewModel survives configuration changes. A ViewModel should not need one.
Mid
Passing it as an argument to a function that uses it immediately and returns does not leak, but it is still a design smell. Hilt does not even allow it: ViewModelComponent has no Activity binding, so you can only inject @ApplicationContext or AndroidViewModel's Application. If a ViewModel wants to show a dialog or navigate, it should expose state or an event for the UI to act on.
Senior
Even a one-shot call is risky if the function launches a coroutine that outlives the call. I keep ViewModels free of Android UI types: they depend on repositories and expose state, and the UI collects it with repeatOnLifecycle or collectAsStateWithLifecycle. That also makes them testable on the plain JVM. In review I flag any Context parameter in a ViewModel, and lint's StaticFieldLeak check catches Contexts in static fields and in ViewModels.
Learn it: Context: application vs activity
How does a Context leak cause an OutOfMemoryError?
Junior
Each rotation destroys the old Activity and creates a new one. If a long-lived object still holds the old Activity, it cannot be garbage collected, so memory grows each time.
Mid
The leak chain is long-lived object to Activity to its window and View tree to the bitmaps and drawables the views hold. One leaked screen can hold a lot of memory. If the leaks accumulate, for example listeners added on every rotation and never removed, the heap fills up and the app crashes, often far away from the code that leaked. Fix the reference and confirm with LeakCanary.
Senior
The GC frees anything not reachable from a GC root, and a static field or singleton is reachable for the whole process. A WeakReference would break the chain, but it hides the design problem; the real fix is to not hold the reference, or to clear it at the matching lifecycle event. I catch regressions with LeakCanary in debug builds, its instrumentation rule in UI tests, and StrictMode's detectActivityLeaks in development, and I check heap dumps in the Memory Profiler when a crash report shows OOM.
Learn it: Context: application vs activity
What happens if you call startActivity from a Service without FLAG_ACTIVITY_NEW_TASK?
Junior
It throws AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag.
Mid
A Service is not part of any task, so the system does not know which task to put the new Activity in. FLAG_ACTIVITY_NEW_TASK tells it to start the Activity in a new task, or bring an existing task with the same affinity to the front. The same applies to a BroadcastReceiver, a worker, or the Application Context. The launchMode in the manifest does not remove the need for the flag.
Senior
The bigger issue is that since Android 10, apps in the background are blocked from starting activities except in a few listed cases, so the call usually does nothing useful even with the flag. The right design is a notification with a PendingIntent (a full-screen intent for things like calls and alarms, which needs its own permission on Android 14+). When the app is in the foreground, the UI should navigate itself in response to state, not a service.
Learn it: Context: application vs activity
Explain what a task is and how the back stack works.
Junior
A task is a stack of activities the user sees as one job. The top one is the visible screen. Pressing Back finishes the top activity and shows the one below. The system manages this stack.
Mid
Each task is one entry in Recents. Launch modes in the manifest and intent flags decide whether a launch pushes a new instance, reuses an existing one, or switches tasks. taskAffinity decides which task an activity belongs to when it is started with NEW_TASK or is singleTask. Since Android 12, Back on the root launcher activity moves the task to the background instead of finishing it.
Senior
I inspect the real state with adb shell dumpsys activity activities, which lists tasks, their affinity and the activities in order. Most back-stack bugs come from mixing launch modes with flags, notifications that start a deep screen without a parent stack, and custom affinities. In modern apps I keep one or few Activities and let Navigation own the in-app back stack, so tasks only matter at the edges: launcher, notifications, deep links and other apps.
Learn it: Tasks and the back stack
What are the four launch modes and when would you use each?
Junior
standard creates a new instance each time. singleTop reuses the instance if it is on top. singleTask keeps one instance and clears what is above it. singleInstance puts the activity alone in its own task.
Mid
standard is right for most screens. singleTop fits a screen that receives repeated intents while visible, such as a search results screen or the target of a notification, so it gets onNewIntent instead of a duplicate. singleTask fits an activity that must exist once and act as an entry point, but it finishes everything above it. singleInstance is rare, for an activity that must never share a task.
Senior
I default to standard and use flags for the special launches, because a manifest launch mode applies to every caller. Whenever an activity can be reused, it must handle onNewIntent and call setIntent. Android 12 added singleInstancePerTask, which allows one instance at the root of each task. Some combinations change task behaviour in surprising ways, so I verify each one with dumpsys rather than from memory.
Learn it: Tasks and the back stack
What happens if you start an Activity from a Service?
Junior
You need FLAG_ACTIVITY_NEW_TASK, because a Service is not an Activity and has no task to put the new screen in. Without it the call throws an exception.
Mid
Without the flag the system throws AndroidRuntimeException. With it, the activity goes into the task matching its affinity, which by default is your app's existing task, or a new one if none exists. But since Android 10, apps in the background are blocked from starting activities except in a few listed cases, so the call often does nothing.
Senior
The right design is a notification with a PendingIntent: the user decides when to open the screen, and the system holds the PendingIntent even if your process dies. I build it with TaskStackBuilder or a Navigation deep link so Back has a parent, and use FLAG_IMMUTABLE when targeting API 31+. For urgent cases such as calls and alarms, a full-screen intent notification is the allowed path, and it needs the USE_FULL_SCREEN_INTENT permission, which Android 14 restricts to those app types.
Learn it: Tasks and the back stack
How do you handle Back navigation in a modern Android app?
Junior
Use OnBackPressedDispatcher.addCallback instead of overriding onBackPressed, or BackHandler in Compose. A callback can be enabled or disabled.
Mid
Callbacks are tied to a LifecycleOwner and the most recently added enabled one runs first. In a Fragment I scope the callback to viewLifecycleOwner so it is removed with the view. I only enable the callback while there is something to handle, such as an open panel, and otherwise let the system handle Back. onBackPressed has been deprecated since API 33.
Senior
Predictive back shows a preview of where Back will go, so the system must know before the gesture whether the app will intercept it. That is why callbacks must keep isEnabled up to date ahead of time. Apps opt in with android:enableOnBackInvokedCallback="true", and on Android 16 it is the default for apps targeting API 36; then onBackPressed and KEYCODE_BACK are not delivered. For custom animations I use the progress callbacks on OnBackPressedCallback or PredictiveBackHandler in Compose, and I test Back from every entry point.
Learn it: Tasks and the back stack

Compose basics

What does declarative UI mean in Compose?
Junior
You describe what the screen should look like for the current state. When the state changes, Compose redraws it. You do not find views and change them yourself.
Mid
The UI is a function of state. A composable reads state and emits UI. When the state changes, Compose runs the affected composables again and updates the tree. This removes a whole class of bugs where the views and the data disagree.
Senior
Declarative here means the framework owns the diff. The cost is a different discipline: composables must be idempotent and free of side effects, because they can run often, be skipped or be cancelled. Single source of truth plus unidirectional data flow keeps this testable, and I check it by looking at recomposition counts in Layout Inspector.
Learn it: Thinking in Compose
What is recomposition?
Junior
It is Compose running a composable function again when the state it reads has changed, so the UI shows the new value.
Mid
Compose tracks which composables read which state. When a state value changes, only those composables are marked invalid and re-run. Others are skipped if their inputs did not change.
Senior
Recomposition is scoped by restartable composable functions, and it is optimistic: it can be abandoned and restarted when state changes again. That is why composable bodies must not have side effects. Performance work means reducing unnecessary scopes and unstable parameters, and verifying with recomposition counts rather than guessing.
Learn it: Thinking in Compose
Why must a composable have no side effects in its body?
Junior
Because the body can run many times. A network call or a log in the body would repeat every time the UI is redrawn.
Mid
Composables can run frequently, in any order and be skipped or cancelled. A side effect in the body can fire many times or at the wrong time. Use LaunchedEffect, DisposableEffect or the ViewModel, which give the work a clear start and stop.
Senior
Compose reserves the right to run composables in parallel, and a recomposition can be thrown away halfway. A write to a plain shared variable during composition stays behind even when that recomposition is discarded, so the app sees a change the UI never showed. Effect handlers tie work to the composition lifecycle: they start after the composition is applied and are cancelled or disposed when the composable leaves. I treat any non-pure statement in a body as a review comment.
Learn it: Thinking in Compose
How is state different from a normal variable in a composable?
Junior
A normal variable is not watched, and it is reset every time the function runs. State is watched and remembered, so the UI updates when it changes.
Mid
A plain variable is re-created on every call and Compose does not observe it. mutableStateOf creates an observable holder, and remember keeps it across recompositions. Both are needed for local UI state.
Senior
Compose state is part of the snapshot system. Reads inside composition are recorded, and writes invalidate the scopes that read them. A plain var has neither. Local state needs remember, and rememberSaveable if it must survive recreation. State that outlives the screen belongs in a ViewModel.
Learn it: Thinking in Compose
What is a composable and how is it different from a regular Kotlin function?
Junior
A composable is a function annotated with @Composable that describes UI. It can only be called from another composable. It does not return a view; it emits UI into the composition.
Mid
The runtime may call a composable many times, in any order, or skip it if its inputs did not change. So the body must be free of side effects and cheap to run. A regular function has no such contract and is called exactly when you call it.
Senior
The Compose compiler plugin rewrites each composable: it adds a Composer parameter, wraps the body in groups so the runtime can store remembered values by position, and makes most composables restartable and skippable. During composition the runtime records which State objects each restart scope reads, so a state write re-runs only those scopes. When a parent recomposes, a skippable child is skipped if its arguments compare equal to last time. Layout Inspector's recomposition counts show what actually re-runs.
Learn it: Composables and modifiers
Why does modifier order matter? Give a concrete example.
Junior
Modifiers are applied in order, so swapping them changes the result. Padding before background leaves a gap around the gray box; padding after background makes the gray box bigger with the text indented inside.
Mid
Each modifier wraps the ones after it, so the chain goes from outer to inner. With .padding(16.dp).background(gray), the padding shrinks the space first and the background paints only the inner area. Swapping them paints the full area and then indents the content. The same applies to clickable: before padding, the padding is part of the tap area; after padding, it is not.
Senior
A modifier chain becomes a chain of Modifier.Node objects on one layout node. Layout modifiers like padding and size change the constraints passed inward, draw modifiers paint in the space they get, and pointer modifiers handle touches in their bounds. That is why the first size modifier wins and why a clickable placed too far in shrinks the touch target below the 48 dp guideline. Layout Inspector lists the modifiers on a node, and screenshot tests catch regressions.
Learn it: Composables and modifiers
What does it mean that a composable can be skipped?
Junior
If a composable gets the same inputs as last time, Compose may not call it again during a recomposition. It keeps what it showed before. This saves work.
Mid
When a parent recomposes, Compose compares each child's arguments with the previous ones. If they are equal and nothing the child reads has changed, the child is skipped. A child also runs again on its own when a state it reads changes, even if the parent does not recompose.
Senior
With strong skipping mode, which is on by default in recent Compose compiler versions (Kotlin 2.0.20 and later), restartable composables can be skipped even with unstable parameters: stable ones are compared with equals and unstable ones by instance. Lambdas in composables are remembered automatically. Some composables are not skippable at all, such as inline layouts like Column and functions that return a value. Compose compiler reports and Layout Inspector counts show which functions are skippable and how often they really run.
Learn it: Composables and modifiers
How do you design a stateless composable?
Junior
A stateless composable takes all its data as parameters and holds no mutableStateOf. User actions go out as lambda callbacks, like onClick.
Mid
State down, events up. The parent or a ViewModel owns the state. The composable receives the current value and callbacks such as onValueChange. This makes it easy to preview and to test with createComposeRule by passing fixed values.
Senior
I often ship two versions: a stateless one that takes value and onValueChange, and a thin stateful wrapper that remembers the state for simple callers, like the material TextField pattern. Content slots (composable lambda parameters) keep components flexible without many flags. When many related values travel together, I group them in an immutable class or a state holder class instead of a long parameter list.
Learn it: Composables and modifiers
What is the difference between arrangement and alignment in Row and Column?
Junior
Arrangement controls how children are spaced along the main axis, like horizontal spacing in a Row. Alignment controls where children sit on the cross axis, like vertical position in a Row. They are separate parameters on the container.
Mid
Arrangement is one parameter on the container that decides main-axis positions for the whole group: Start, Center, SpaceBetween, SpaceEvenly, spacedBy and so on. Alignment is the cross-axis position: verticalAlignment in Row, horizontalAlignment in Column, and a child can override it with Modifier.align. Neither changes a child's size, only where it is placed.
Senior
Row measures its children first (unweighted, then weighted with the space left, minus any spacedBy gaps), then sizes itself. In the placement step it calls Arrangement.arrange to get main-axis offsets and uses the Alignment for each child's cross-axis offset. A custom Arrangement or a custom Layout can do the same math. Layout Inspector shows the resulting child bounds when I need to check it.
Learn it: Layouts: Row, Column, Box
How does Modifier.weight work in Row versus Column?
Junior
weight makes a child take a share of the remaining space. In a Row it controls width; in a Column it controls height. Different weights give different proportions, so 1f and 2f split the space one-third and two-thirds.
Mid
weight is only available inside Row and Column because it is defined on RowScope and ColumnScope. The parent first measures unweighted children, then gives each weighted child the remaining space times its weight divided by the total weight. Weights must be greater than zero. With fill = false the share is a maximum instead of an exact size.
Senior
weight is parent data: the child carries it and the Row reads it, so its position in the modifier chain does not matter. Weighted children get fixed constraints for their share when fill is true. In a horizontally scrolling Row the maximum width is unbounded, so there is no remaining space for weights to share. For proportional layouts beyond this, such as a grid of equal cells across rows, I use LazyVerticalGrid, FlowRow, or a custom Layout.
Learn it: Layouts: Row, Column, Box
When would you use Box instead of Row or Column, and when would you reach for a custom Layout?
Junior
Use Box to stack children on top of each other, like a spinner over an image. Use Row or Column when children are in a line. Use a custom Layout when none of the three can express the arrangement.
Mid
Box is for overlays: badges, spinners, scrims. It sizes itself to the largest child, and matchParentSize lets an overlay cover it without growing it. Row and Column are for sequences. A custom Layout fits patterns like a circular menu or overlapping avatars, after checking FlowRow, FlowColumn and the lazy grids.
Senior
Compose enforces measuring each child only once per pass, so nesting Boxes, Rows and Columns does not multiply measure work the way nested weights did in LinearLayout. The real costs are intrinsic measurements and subcomposition, as in BoxWithConstraints or SubcomposeLayout. So I pick a custom Layout for what it can express, not for speed by default, and confirm any performance claim with a trace or macrobenchmark.
Learn it: Layouts: Row, Column, Box
Does the position of Modifier.weight in a modifier chain matter?
Junior
No. Modifier.weight(1f).padding(8.dp) and Modifier.padding(8.dp).weight(1f) give the same layout. In both cases the padding is inside the child's share.
Mid
weight is not a size modifier; it is information for the parent Row or Column. The parent reads it no matter where it sits in the chain, decides the child's share, and then the child's own modifiers, such as padding, apply inside that share. Order still matters for the other modifiers, like padding and background.
Senior
weight is a ParentDataModifier. Parent data from the whole chain is collected and handed to the parent's measure policy, while layout modifiers like padding and size wrap the child's measurement. So you can move weight anywhere without changing layout. What can override it are other size modifiers in the chain, for example a width that is coerced into the fixed constraints the weight produces. I check unusual cases in Layout Inspector.
Learn it: Layouts: Row, Column, Box
What happens when a mutableStateOf value changes?
Junior
The composables that read that state value recompose. Compose remembers which composables read it during composition and re-runs only those.
Mid
During composition, the snapshot system records reads per recompose scope. A write invalidates the scopes that read the value, and Compose re-runs them on the next frame. Those scopes call their children again, but children whose arguments are unchanged are skipped. So reading state at the top of a screen re-runs the top scope, not necessarily everything under it.
Senior
Writes go through the snapshot system: when the snapshot is applied, the Recomposer invalidates the scopes that read the changed objects and schedules a recomposition for the next frame. Several writes before that frame result in one recomposition. To keep scopes small I read fast-changing state low in the tree, pass lambdas instead of values, or read in layout or draw lambdas. I verify with Layout Inspector's recomposition counts and composition tracing in a system trace.
Learn it: State and remember
When do you use rememberSaveable instead of remember?
Junior
Use rememberSaveable when the value should survive rotation or the system killing the process in the background. remember keeps the value only across recompositions.
Mid
rememberSaveable saves the value in the saved instance state Bundle through the SaveableStateRegistry. The value must be Bundle-compatible, like primitives, String or a Parcelable, or you write a Saver with mapSaver or listSaver. If it cannot be saved, it throws an exception when the state is saved.
Senior
Saved state has a size limit and a large Bundle can crash with TransactionTooLargeException, so I save small things like ids, a tab index or a query, and reload data from the repository. In Navigation Compose each back stack entry has its own saveable state, so rememberSaveable values come back when you return to a destination, while remember values do not. I test it with StateRestorationTester or by enabling Don't keep activities.
Learn it: State and remember
Why use derivedStateOf?
Junior
It calculates a value from other state and notifies readers only when the result changes. For example, a check like firstVisibleItemIndex > 0 changes far less often than the index itself.
Mid
Without it, a composable that reads the scroll index recomposes every time the index changes. With remember { derivedStateOf { ... } }, the composable reads only the derived value, which changes only when the boolean flips. It must be inside remember, or a new derived state is made on every recomposition.
Senior
derivedStateOf records the states it reads, recomputes lazily when one of them changes, and compares the new result with the old one (structural equality by default) before notifying readers. That bookkeeping has a cost, so it only helps when inputs change more often than the output. A case like fullName = first + last changes on every input change and gains nothing. If the calculation uses a non-state value, such as a parameter, that value must be a key of remember, or the derived state keeps using the old one.
Learn it: State and remember
What is "state down, events up"?
Junior
State lives in the parent and is passed down as parameters. Children send events like clicks up through lambda callbacks. This keeps children stateless and easy to test.
Mid
A stateless composable re-runs only when its arguments change, which makes its behaviour predictable, and Compose can skip it when the parent recomposes with the same arguments. The owner of the state is the single source of truth, and the child cannot get out of sync with it.
Senior
Hoist state to the lowest common ancestor of everything that reads or writes it. Higher than that adds readers and recomposition for no reason; lower creates two sources of truth. Screen state and business logic go to a ViewModel, and pure UI element state, like a LazyListState, can stay in the composable or a plain state holder class. I check recomposition counts to confirm that scrolling a list does not re-run the toolbar.
Learn it: State and remember
What is state hoisting in Compose and why do it?
Junior
State hoisting means moving the state from a child composable up to its parent. The child then receives the value as a parameter and sends changes back through a callback. This lets the parent read, reset, or share the value.
Mid
The parent owns the state and passes the value down; the child renders it and calls an onXChange lambda. That gives a single source of truth, makes the child reusable, and lets previews and UI tests drive it with any value. The usual pitfall is copying the parameter into a local remember, which creates a second source of truth that drifts.
Senior
Hoist to the lowest common ancestor of all readers and at least as high as the highest writer. Higher adds readers and recomposition for nothing; lower duplicates state. Pure UI element state can stay in the composable or a plain state holder class, while screen state with business logic goes to a ViewModel. I often keep a thin stateful wrapper for simple callers next to the stateless version, like the material TextField pattern.
Learn it: State hoisting
How does state hoisting affect which composables recompose?
Junior
When the parent owns the state and reads it, the parent recomposes when it changes. The child recomposes because it receives a new parameter value.
Mid
Recomposition follows where the state is read, not where it is declared. If the parent reads the value to pass it down, the parent's scope re-runs, and the child re-runs because its argument changed. Siblings whose arguments did not change are skipped.
Senior
Compose records reads per recompose scope during composition and invalidates those scopes on a write. Hoisting moves the read up, so the parent scope runs too. That cost is usually small because unchanged children are skipped. For values that change every frame, I defer the read: pass a lambda like { offset } or read the value in a layout or draw lambda. I check the result with Layout Inspector's recomposition counts.
Learn it: State hoisting
When should you NOT hoist state?
Junior
When no other composable needs the value, keep it local with remember. For example, whether a dropdown menu is expanded usually only matters to that menu.
Mid
Local UI element state, like expanded or collapsed, or a LazyListState that no parent uses, can stay in the composable. Hoisting it adds parameters and spreads reads to places that do not need them. The pitfall is hoisting everything out of habit.
Senior
It is a question of ownership and lifetime. If another composable reads it or a parent must reset it, hoist it to their common ancestor. If it must survive navigation or process death, it goes to a ViewModel with SavedStateHandle, or rememberSaveable for small UI values. If only one component uses it and it is purely visual, keep it local. A common middle ground is to accept the state with a default, like scrollState: ScrollState = rememberScrollState(), so callers can hoist it when they need to.
Learn it: State hoisting
How would you structure a multi-field form with state hoisting?
Junior
Keep the field values in the parent, for example as separate remember { mutableStateOf(...) } variables, and pass each value down to its field composable together with an onXChange callback.
Mid
For a real screen I hold a FormState data class in a ViewModel and expose it as a StateFlow. The screen collects it with collectAsStateWithLifecycle and passes each field and its callback to stateless field composables. A change to one field re-runs the screen scope and that field; the other fields get equal arguments and are skipped.
Senior
The ViewModel is the only writer and validation is a computed property of FormState. Text input needs care: update the state synchronously in onValueChange, for example with MutableStateFlow.update, and never after a delay or a suspend call, or the cursor can jump and characters can get lost. The ViewModel is obtained with viewModel() or hiltViewModel() and scoped to the navigation graph if several steps share it, and the important values go in SavedStateHandle for process death.
Learn it: State hoisting
Why do you pass a key to items in a LazyColumn?
Junior
The key gives every item a stable id. Without it, Compose uses the position, so state and scroll position can attach to the wrong item when the list changes.
Mid
Compose uses the key to match old and new items when the list changes. State stored with remember or rememberSaveable inside an item, scroll position, and item animations follow the key. Keys must be unique and stable, such as a database id. On Android the key type must be saveable in a Bundle because it is used to save item state.
Senior
Keys are the identity contract between my data and the composition. I use ids that come from the data layer, never the index, and I make sure the data layer guarantees uniqueness, for example by deduplicating merged pages. I also keep row state out of the item when it is really data state, such as selection, so correctness does not depend on the key alone. I verify with a test that inserts and removes items while one is selected, and I check that animateItem behaves correctly after the change.
Learn it: Lists with LazyColumn
How is LazyColumn different from RecyclerView?
Junior
Both show long lists without creating every item. LazyColumn is written in Compose, so you describe items in code and there is no adapter or ViewHolder.
Mid
RecyclerView recycles View objects through ViewHolders. LazyColumn composes only visible items and disposes those that leave. Because there is no ViewHolder, item state is kept by remember and key. contentType lets Compose reuse nodes between items of the same type, which is the closest idea to view types.
Senior
The cost model is different. In RecyclerView the expensive step is binding and inflating views. In a lazy list it is composition and measure of each new item, and lazy lists prefetch upcoming items to hide part of that cost. So I keep item composables cheap and stable, avoid unstable parameters that cause extra recomposition, and measure with release builds and a baseline profile, because debug-mode lists look much slower than they are. For huge feeds I also check that item content types are set, and I compare frame timing before and after changes.
Learn it: Lists with LazyColumn
Why can you not put a LazyColumn inside a Column with verticalScroll?
Junior
The two scroll in the same direction. The lazy list needs a fixed height to know what is visible, and the scrolling parent gives it unlimited height, so it crashes.
Mid
verticalScroll measures its child with infinite maximum height. A lazy list cannot decide which items are visible with unlimited height, so Compose throws an exception. Use a single LazyColumn and add the other content as item blocks, or give the list a fixed height if it must be nested.
Senior
Laziness only works if the viewport is bounded. With unlimited height the list would have to compose every item, which defeats it, so the framework refuses. The design fix is to flatten the screen into one lazy list with item, items and stickyHeader blocks, which also gives one scroll state and correct nested behaviour. If a bounded nested list is truly needed, I set an explicit height and accept that it will scroll separately.
Learn it: Lists with LazyColumn
How do you avoid recomposing the whole screen on every scroll event?
Junior
Do not read the scroll position directly in the screen. Wrap it so the screen only changes when a value you care about changes.
Mid
Use derivedStateOf inside remember to turn the scroll position into a boolean, such as whether the first item is visible. The composable that reads it only recomposes when that boolean flips. For side work such as analytics, use snapshotFlow in a LaunchedEffect.
Senior
State reads decide the scope of recomposition. Reading firstVisibleItemIndex in the parent makes the parent a reader for every change. I push reads as low as possible or derive a coarser value. I also remember that derivedStateOf only helps when the output changes less often than the input. I confirm in Layout Inspector with recomposition counts rather than guessing.
Learn it: Lists with LazyColumn
How does MaterialTheme make its values available to child composables?
Junior
MaterialTheme is a composable that you wrap around your content. Inside it, you read values with MaterialTheme.colorScheme, MaterialTheme.typography, and MaterialTheme.shapes. Any composable below the MaterialTheme call can access these values.
Mid
Under the hood, MaterialTheme calls CompositionLocalProvider for the internal LocalColorScheme, LocalTypography, and LocalShapes. MaterialTheme.colorScheme is just a read of LocalColorScheme.current, so it returns the value provided by the nearest MaterialTheme above. The Material components themselves read the same locals for their defaults, which is why a Button or Card follows your theme with no extra code.
Senior
Values are resolved from the nearest provider at composition time. The color scheme local is a static CompositionLocal, so changing it invalidates the content under the provider rather than tracking individual readers. That is fine because theme changes are rare. Nesting is a tool: a nested MaterialTheme inherits every value you do not pass, so you can override shapes or colors for one subtree. The bug is a nested theme with a hardcoded scheme. For extra design tokens that Material does not model, such as brand or success colors, I add my own CompositionLocal in the app theme instead of hardcoding them in screens.
Learn it: Material 3 theming
What is dynamic color and how do you implement it correctly?
Junior
Dynamic color is the Material You feature on Android 12 where the app's colors are derived from the user's wallpaper. You call dynamicLightColorScheme or dynamicDarkColorScheme with the current Context to get a ColorScheme.
Mid
You guard the call with Build.VERSION.SDK_INT >= Build.VERSION_CODES.S because the APIs do not exist on older devices. For pre-12 you fall back to lightColorScheme or darkColorScheme. The dynamic scheme is built from system color resources. When the user changes wallpaper colors, the system updates those resources and normally recreates running activities, so the new scheme appears without extra code.
Senior
I expose a dynamicColor parameter in the theme function so a product decision or a user setting can turn it off, for example when brand colors must stay fixed. Dynamic schemes are generated to meet Material contrast rules, but any custom colors I add on top are not, so I keep brand colors in my own tokens and check contrast in screenshot tests across several wallpapers and both light and dark. I also make sure non-Compose parts, such as the XML app theme used for the splash screen and any View screens, use a Material3 DayNight theme so the app does not flash different colors at startup.
Learn it: Material 3 theming
A screen shows white text on a white background in dark mode. How do you debug it?
Junior
First check whether the screen is inside the MaterialTheme wrapper. If it is, look for hardcoded Color values like Color.White or Color(0xFFFFFFFF) in that screen and replace them with MaterialTheme.colorScheme roles such as onSurface.
Mid
Beyond hardcoded colors, check whether the screen accidentally creates its own MaterialTheme with a light colorScheme, shadowing the app-level dark scheme. Also verify that the background and text are not both reading the same role, for example both using surface instead of surface and onSurface. A quick way to find offenders is to grep the module for Color. literals outside the theme file.
Senior
In a large codebase, add a Detekt or custom lint rule that flags any Color constructor call outside the designated theme package. At runtime, use Layout Inspector to see which composable draws the text and with which parameters. If only some screens break, check for a nested theme with a fixed scheme, or a color computed once and cached outside the theme, for example stored in a ViewModel or remembered without a key, so it does not update when the theme changes. Add light and dark screenshot tests so it cannot come back.
Learn it: Material 3 theming
How do you customise typography or shapes without breaking the rest of the Material3 defaults?
Junior
You call Typography() or Shapes() to get the default object, then use .copy() to override the specific property you want to change. For example, Typography().copy(headlineMedium = Typography().headlineMedium.copy(fontWeight = FontWeight.SemiBold)).
Mid
The Typography and Shapes constructors have Material 3 defaults for every parameter, so Typography(titleLarge = ...) or Shapes(medium = ...) changes only what you pass. The real trap is the style itself: titleLarge = TextStyle(fontSize = 24.sp) drops the default line height, letter spacing and weight. Start from the default style and copy it. To change the font everywhere, apply the new fontFamily to every role, not just a few.
Senior
In a multi-module project, centralise the customised Typography and Shapes in a shared theme module so every feature module gets the same overrides. If you need per-brand theming, build a sealed interface for theme variants and select the right Typography and Shapes at the setContent call. Verify with a screenshot test that all five shape slots and all type roles render as expected, because a style built from a bare TextStyle silently loses line height and letter spacing.
Learn it: Material 3 theming
What is a NavHost and how does it relate to the back stack?
Junior
A NavHost is a composable that shows one screen at a time. The NavController holds a back stack of entries. When you navigate, a new entry is pushed; when you press back, the top entry is popped and the previous screen is shown.
Mid
The NavHost observes the NavController's back stack and composes only the top entry, plus the outgoing one during a transition. Entries below the top stay on the stack with their saved state and ViewModels, but their UI is not composed. A popped entry is destroyed: its ViewModels are cleared and its saved state is discarded.
Senior
Each NavBackStackEntry is a LifecycleOwner, ViewModelStoreOwner and SavedStateRegistryOwner. The top entry is RESUMED, entries below are moved down to CREATED, and popped entries are DESTROYED. That is why a ViewModel obtained inside a destination lives exactly as long as that entry, and why hiltViewModel or viewModel inside a destination gives a per-screen ViewModel. A ViewModel shared by a flow is scoped to the nested graph's entry via getBackStackEntry. The whole stack, including each entry's arguments and saved state, is saved and restored across process death, so I test screens with the 'Don't keep activities' developer option.
Learn it: Navigation in Compose
Why should you pass an ID in a route instead of the full object?
Junior
The route is saved with the app's state. A big object takes more space and may not be saveable at all. An ID is small and always works.
Mid
Route fields become navigation arguments that are stored in saved state. Only primitives, strings, enums and similar types work out of the box; a domain object needs a custom NavType. Even then it bloats saved state and can trigger TransactionTooLargeException, and the copy goes stale if the data changes. Passing an ID lets the screen load fresh data from the repository.
Senior
It is about a single source of truth. The repository or database owns the data; the route only says which item to show. The ViewModel reads the id with savedStateHandle.toRoute and observes the item, so updates from elsewhere appear automatically and process death is handled for free. It also keeps deep links simple, because a deep link can only carry an id anyway. I keep a CI test that round-trips every route through kotlinx.serialization and fails if a route grows a large or custom-typed field.
Learn it: Navigation in Compose
What happens to a LaunchedEffect inside a destination when the user navigates?
Junior
When the screen leaves the composition, the LaunchedEffect is cancelled and any coroutine it started is stopped.
Mid
That happens both when the entry is popped and when you navigate forward to another screen, because only the top entry is composed. When the user comes back, the destination is composed again and the LaunchedEffect starts again. So loading data in LaunchedEffect(Unit) repeats on every return. Work that should run once per screen belongs in the ViewModel, which survives while the entry is on the stack.
Senior
Cancellation is cooperative: the coroutine stops at its next suspension point, or when it checks isActive or calls ensureActive, so a CPU-bound loop must check explicitly. I treat composition effects as UI-scoped only: collecting flows tied to the screen, animations, showing a snackbar. Anything with business meaning goes to viewModelScope, and anything that must outlive the screen goes to WorkManager. To see the behaviour I add a DisposableEffect with a log in onDispose and watch it fire on both forward navigation and back.
Learn it: Navigation in Compose
How do type-safe routes differ from string-based routes, and when would you still use strings?
Junior
Type-safe routes use a class annotated with @Serializable instead of a string path. The compiler checks the route and its argument types, so typos are caught early. String routes use a path like detail/{id} and are only checked at runtime.
Mid
With type-safe routes you write composable<Detail> and navigate with navController.navigate(Detail(id)). Reading the parameter is backStackEntry.toRoute<Detail>().id instead of backStackEntry.arguments?.getString("id"). You need the Kotlin serialization plugin; without it the annotation compiles but no serializer is generated, and navigation fails at runtime.
Senior
Type-safe routes are stable from Navigation Compose 2.8.0. Under the hood the library still builds a route pattern and an arguments bundle from the class, so deep links and saved state work the same way, but argument names and types can no longer drift between the graph and the call sites. Custom field types need a NavType in typeMap, which I treat as a code smell. In a legacy codebase I migrate graph by graph, since both styles can live in one NavHost, and new screens use type-safe routes only.
Learn it: Navigation in Compose
What happens when the key of a LaunchedEffect changes?
Junior
The old coroutine is cancelled and a new one is launched with the new key. This is how you reload data when an id changes.
Mid
On the recomposition where the key changes, Compose cancels the old coroutine's Job and launches a new coroutine. Cancellation is cooperative: the old coroutine gets a CancellationException at its next suspension point, so finally blocks run but code after the suspension does not. If the key is equal to last time, the effect keeps running.
Senior
LaunchedEffect is a remember keyed on its keys that stores an object observing the composition. When it is remembered, it launches the coroutine in a scope using the composition's effect context, which runs on the main thread by default. When a key changes, the old object is forgotten, which cancels its coroutine, and a new one is remembered and launches. The same happens on leaving the composition, and in a recomposition that is abandoned the effect is never started. Keys use equals, so a data class key restarts only on a real value change.
Learn it: Side effects: LaunchedEffect and friends
When would you choose DisposableEffect over LaunchedEffect?
Junior
Use DisposableEffect when you register something that is not a coroutine, like a LifecycleObserver or a listener, and need to remove it again when the composable leaves.
Mid
LaunchedEffect gives you a coroutine scope for suspending work. DisposableEffect runs a normal block and requires an onDispose block for cleanup. Both restart when a key changes and stop when the composable leaves the composition. For callback-based APIs, DisposableEffect is the natural fit.
Senior
DisposableEffect runs synchronously on the main thread when the composition is applied, so its block must be cheap: register and return. A LaunchedEffect can do cleanup too, with try/finally around awaitCancellation(), which is handy when setup is suspending. A callback API can also be wrapped in callbackFlow with awaitClose and collected in a LaunchedEffect. For lifecycle specifically, lifecycle-runtime-compose offers LifecycleEventEffect and LifecycleStartEffect, which do the observer bookkeeping for you.
Learn it: Side effects: LaunchedEffect and friends
What is rememberUpdatedState and when do you need it?
Junior
It keeps the latest value of something, such as a callback, so a running effect can use it without being restarted.
Mid
A LaunchedEffect(Unit) that calls an onTimeout parameter after a delay keeps the lambda from its first composition. If the parent passes a new lambda, the effect would call the old one. With val currentOnTimeout by rememberUpdatedState(onTimeout), the effect reads the State, which is updated on every recomposition, so it calls the latest lambda without restarting.
Senior
The choice is whether a change should restart the work. If it should, make the value a key. If the work must keep running, like a timer, a long collect or a listener, and only needs the latest callback or config, use rememberUpdatedState. It is not needed for Compose state such as a by mutableStateOf variable: reading it inside the coroutine already returns the current value. In reviews I look for parameters used inside long-running effects that are neither keys nor wrapped.
Learn it: Side effects: LaunchedEffect and friends
How does derivedStateOf reduce recomposition?
Junior
It calculates a value from other state and only notifies readers when the result changes, not on every input change.
Mid
Without it, a composable that reads the input state recomposes on every input change. With derivedStateOf, the composable reads only the derived state. If the input changes but the result is the same, the composable is not invalidated. It fits noisy inputs mapped to a coarse result, like a scroll index mapped to a show-button flag.
Senior
The derived state records the states its block reads, recalculates when one of them changes and is read again, and compares the new result with the previous one using the mutation policy, structural equality by default. Only a different result invalidates readers. That costs some bookkeeping, so it pays off only when the output changes less often than the inputs. It must be remembered, and non-state values used inside must be keys of remember. I confirm the gain with Layout Inspector recomposition counts.
Learn it: Side effects: LaunchedEffect and friends

Views you will still meet

What is the difference between findViewById, ViewBinding and DataBinding?
Junior
findViewById looks up a view by id at runtime and can return null or the wrong type. ViewBinding generates a class for each layout with ready fields, so it is type safe and null safe. DataBinding does the same and also lets you write expressions in the XML.
Mid
ViewBinding generates one binding class per layout at build time, with no annotation processor and almost no build cost. A field is non-null if the view exists in every variant of the layout, and nullable if it does not. DataBinding needs the layout wrapped in a layout tag and supports binding expressions and observable data. Most teams use ViewBinding and keep state in a ViewModel.
Senior
I choose ViewBinding by default because it is a thin, predictable layer with no hidden logic. DataBinding moves logic into XML, which hurts testing and makes build errors harder to read. For an old codebase with Kotlin synthetics I migrate module by module, because the plugin was removed in Kotlin 1.8 and blocks toolchain upgrades. Binding classes are generated into the build folder, so I check the generated code when a nullability question comes up.
Learn it: XML layouts and ViewBinding
Why do you set the binding to null in onDestroyView?
Junior
Because the Fragment can stay alive after its view is destroyed. If the binding is still held, the old views cannot be freed.
Mid
A Fragment on the back stack keeps its instance but its view is destroyed and later recreated through onCreateView. A binding field points to the whole old view tree. Nulling it in onDestroyView lets the garbage collector free it. The same applies to adapters and listeners held in Fragment fields.
Senior
The Fragment has two lifecycles, the Fragment and its view, and anything that references views must follow the view lifecycle. I use viewLifecycleOwner for collection and observers, clear the binding, and detach adapters. I verify with LeakCanary in debug builds, and I treat a leaked Fragment view as a release-blocking bug because on a deep back stack it multiplies memory cost.
Learn it: XML layouts and ViewBinding
Why is ConstraintLayout recommended over nested LinearLayouts?
Junior
It lets you build complex screens with one level of views, which is faster to draw than many nested layouts.
Mid
Every layout pass measures and positions the tree from the root. Deep nesting means more work, and layouts that use weights can measure their children more than once. ConstraintLayout expresses relations between views in a flat tree, so fewer parents are involved.
Senior
Flat is not automatically faster. ConstraintLayout has its own solver cost, so a simple row is still better as a LinearLayout. I measure with Layout Inspector and system tracing before refactoring, and I look at the measure and layout time of the screen, not only the depth. For scrolling lists I care more about cheap item layouts and view recycling than about the screen shell.
Learn it: XML layouts and ViewBinding
How does RecyclerView recycling work?
Junior
RecyclerView keeps only enough ViewHolder objects to fill the screen plus a few extras. When an item scrolls off-screen, its ViewHolder is kept for reuse. When a new item scrolls in, RecyclerView reuses a ViewHolder and calls onBindViewHolder to fill it with new data.
Mid
A holder that leaves the screen first goes into a small view cache (2 by default), which can return it for the same position without rebinding. Older holders go to the RecycledViewPool, kept per view type (5 per type by default), and are always rebound. onCreateViewHolder is called only when neither has a suitable holder. Because holders are reused, onBindViewHolder must set every property, or the recycled-state bug appears.
Senior
There are several layers: attached and changed scrap used during layout, the view cache, optional ViewCacheExtension, and the RecycledViewPool. I tune them with setItemViewCacheSize and pool.setMaxRecycledViews(type, n), and share one RecycledViewPool between nested horizontal RecyclerViews so carousels do not inflate their own holders. LinearLayoutManager prefetches the next items during idle frame time through GapWorker, and for nested carousels setInitialPrefetchItemCount helps. I verify by counting onCreateViewHolder calls while scrolling; after the first screen they should be rare.
Learn it: RecyclerView essentials
What do ListAdapter and DiffUtil do?
Junior
ListAdapter is an adapter that takes a DiffUtil.ItemCallback. You call submitList with a new list, and it figures out what changed and animates it. You do not call notifyDataSetChanged.
Mid
submitList hands the list to AsyncListDiffer, which runs DiffUtil on a background thread and then dispatches granular notifyItem calls on the main thread. areItemsTheSame decides identity, usually by id; areContentsTheSame decides whether the row must be rebound. You must submit a new list each time, because submitting the same instance is ignored.
Senior
DiffUtil uses Myers' algorithm: roughly O(N + D squared) time, where D is the number of edits, plus an extra cost for move detection that grows with added times removed items. It runs off the main thread, but for very large or endless lists I use Paging 3's PagingDataAdapter, which diffs pages. I add getChangePayload for frequent small changes so rows update in place, keep models immutable so the old list is never mutated during a diff, and unit test the ItemCallback because a wrong areItemsTheSame causes flicker that is hard to spot in review.
Learn it: RecyclerView essentials
What are view types and when do you need them?
Junior
A view type is an integer returned by getItemViewType. RecyclerView uses it to pick the right layout in onCreateViewHolder. You need multiple types when a list shows different row shapes, like a header, a card, and a divider.
Mid
Each view type gets its own pool of ViewHolders, so a header holder is never reused for a card. If getItemViewType and onCreateViewHolder disagree, onBindViewHolder receives a holder of the wrong class and a cast throws ClassCastException. An unhandled type in onCreateViewHolder should throw immediately rather than return a blank holder.
Senior
With many types I model items as a sealed class and map each subclass to a type id with an exhaustive when, so the compiler catches a missing case. When sections come from different sources, ConcatAdapter combines several adapters, each with its own types. I also set a pool size per type based on how many fit on screen, and I check that rarely used types do not hold large layouts in the pool.
Learn it: RecyclerView essentials
What is the recycled-state bug and how do you prevent it?
Junior
It happens when a ViewHolder is reused but still shows state from the previous item, like a checked checkbox. The fix is to set every property in onBindViewHolder, not just the ones that changed.
Mid
It only appears when a holder is actually reused, which depends on scroll distance and list length, so short test lists hide it. Common triggers are a CheckBox set to true in one branch and never set to false, a visibility set to GONE but never back to VISIBLE, and a listener that still refers to the old item. The fix is to assign a definite value to every mutable view on every full bind.
Senior
The root cause is keeping state in the view instead of the data. Checked, expanded and selected flags belong in the item model or the ViewModel, keyed by id; the holder only renders them, and clicks report the id from getItem(bindingAdapterPosition) rather than a captured item. Asynchronous work needs care too: cancel or replace image loads in onBindViewHolder or onViewRecycled so a slow load does not land on a reused holder. A Robolectric test that binds two different items to the same holder catches regressions.
Learn it: RecyclerView essentials
Explain how ComposeView works and what ViewCompositionStrategy controls.
Junior
ComposeView is a View subclass that can host Compose UI. You call setContent to add a Compose tree. ViewCompositionStrategy controls when that composition is disposed.
Mid
The default strategy, DisposeOnDetachedFromWindowOrReleasedFromPool, disposes when the view is detached from the window, or for views inside a RecyclerView, when they are released from the pool. DisposeOnViewTreeLifecycleDestroyed disposes when the view's ViewTreeLifecycleOwner is destroyed; in a Fragment that is the view lifecycle, so it is the recommended choice there. DisposeOnLifecycleDestroyed takes an explicit owner. Passing an owner that lives longer than the view keeps the composition and the old views alive.
Senior
ComposeView creates its composition when it is attached to a window, using the window's shared Recomposer, and reads the ViewTree lifecycle, ViewModelStore and SavedStateRegistry owners from the view tree, which Fragment and ComponentActivity set up. The strategy only decides when that composition is disposed, so it is a trade-off between leaks and lost state. In a ViewPager2 page I use the page fragment's view lifecycle; using the parent fragment keeps every page's composition alive until the parent dies. I verify by logging in a DisposableEffect's onDispose and by running LeakCanary after paging through many screens.
Learn it: Interop: Compose in Views and Views in Compose
What is the difference between factory, update, onRelease and onReset in AndroidView?
Junior
factory creates the View, update sets its properties from state, and onRelease cleans up when the View is removed from the composition.
Mid
factory runs when the AndroidView enters composition and creates or inflates the View. update runs right after and then again whenever state it reads changes, so it must be cheap and safe to repeat. onRelease runs when the View is discarded; you remove listeners and release resources there. onReset is optional: providing it lets Compose reuse the View in lazy layouts, and it runs before reuse so you can clear old state.
Senior
update is run inside a snapshot observer, so reading a state object in it subscribes the View to that state, and a fast-changing value like a playback position makes it run constantly. I narrow what update reads and use idempotent calls. factory runs again after a configuration change because the whole composition is recreated, so View state must come from Compose state or the View's own saved state. For AndroidView inside LazyColumn, passing onReset avoids inflating a new View for every item that scrolls in, but then every piece of item state must be reset there or it leaks into the next item.
Learn it: Interop: Compose in Views and Views in Compose
How would you migrate a large XML layout screen to Compose?
Junior
Do it in steps instead of rewriting everything. Put a ComposeView where one part of the screen was, build that part in Compose, and keep the rest in XML until it is converted.
Mid
Add a ComposeView to the layout and replace sections one by one. Use AndroidView for parts that are still Views, like a complex custom view or a MapView. Theme bridging matters: the Compose part should use a theme that matches the XML theme so colors do not differ. This lets you ship Compose incrementally.
Senior
I start with leaf components and new features, then move up to whole screens, and finally switch navigation once most screens are Compose. Each swap is behind a feature flag so it can be rolled back, and screenshot tests compare old and new versions. Interop has a cost: two UI systems, Espresso for the View parts and Compose tests for the rest, and extra View layers, so I keep AndroidView islands temporary. I measure startup and frame timing in release builds with a baseline profile before and after, because debug Compose is much slower than release.
Learn it: Interop: Compose in Views and Views in Compose
A user reports OutOfMemoryError after navigating between screens. What do you check?
Junior
Check if old screens are still kept in memory. Run LeakCanary, which shows what object is retained and the reference chain that keeps it alive.
Mid
Check whether each ComposeView uses a strategy tied to the right lifecycle. If you used DisposeOnLifecycleDestroyed with the activity or a parent fragment, old compositions stay alive. Also check AndroidView cleanup: listeners or an adapter held by a longer-lived object can keep old Views alive.
Senior
Reproduce with LeakCanary and take heap dumps in the Memory Profiler after repeating the navigation. Read the reference chain instead of guessing: a Fragment view binding not cleared in onDestroyView, a composition held by a parent lifecycle, a callback registered on a singleton, or a lambda that captured an Activity are the usual causes. Fix the owner or add cleanup in onRelease or onDestroyView, then add an instrumented test with LeakCanary's leak detection that repeats the navigation so it cannot regress.
Learn it: Interop: Compose in Views and Views in Compose