Member-only story
Mastering Android Interviews: The Hidden Challenges of Implementing a Custom Stopwatch
In a recent interview, I was presented with an intriguing challenge: implementing a custom stopwatch in Android from scratch, without relying on any libraries or helper functions. As I walked the interviewer through my approach using the MVVM pattern and Kotlin Flow, I could sense their curiosity about my understanding of the deeper aspects of Android development.
It wasn’t long before the conversation shifted to critical topics like memory management and potential memory leaks, testing my knowledge beyond just writing code. The questions that followed were as insightful as they were challenging, pushing me to think about the implications of my design choices and how they would hold up in a real-world scenario.
I will be adding the code and questions along with their answer in this article.

Here is the implementation (A more refined and detailed one).
ViewModel
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
class StopwatchViewModel : ViewModel() {
private val _time = MutableStateFlow(0L) // Time in milliseconds
val time: StateFlow<Long> = _time.asStateFlow()
private var isRunning = false
private var startTime = 0L
private var coroutineScope = CoroutineScope(Dispatchers.Main)
fun startStopwatch() {
if (!isRunning) {
isRunning = true
startTime = System.currentTimeMillis() - _time.value
coroutineScope.launch {
while (isRunning) {
_time.update { System.currentTimeMillis() - startTime }
delay(10L) // Update every 10ms for smooth timing
}
}
}
}
fun stopStopwatch() {
isRunning = false
}
fun resetStopwatch() {
isRunning = false
_time.value = 0L
}
override fun onCleared() {…