androidengineers.Book a session
โ† All interview questions
TestingAdvanced3 min

A test sees Success but never Loading from StateFlow. Is the implementation necessarily wrong?

Answer

Not necessarily. If Loading and Success are assigned before a collector resumes, it may observe only the latest state. That behavior is compatible with StateFlow's contract.

Test the intended behavior

For a final-state requirement, run the operation to completion with a controlled scheduler and assert state.value. Do not require a complete emission history unless the product genuinely needs every transition.

For loading behavior, make a fake repository suspend until the test releases it:

Start load
Run scheduled work until fake request is pending
Assert current state is Loading
Complete fake request
Run remaining work
Assert current state is Success

This establishes a real observable waiting period instead of depending on lucky scheduling. Prefer a controllable fake or completion signal over adding an artificial delay to production code.

Mistake to avoid

Switching test dispatchers until the assertion passes can hide a mistaken contract. Also inspect whether a stateIn(WhileSubscribed(...)) stream has a collector: without one, its upstream may never start, so reading .value alone can leave the initial state unchanged.

Follow-up to practise

What if every event must be processed? Model an event-delivery mechanism with suitable buffering, acknowledgement, and persistence for the requirement. A state holder should not be treated as an audit log.

References

Kotlin: StateFlow conflation

Android Developers: Coroutine testing

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow ๐Ÿ’š

Keep practising