Skip to content

Instantly share code, notes, and snippets.

@Arunshaik2001
Created Jan 21, 2023
Embed
What would you like to do?
class MainViewModel: ViewModel() {
private var job: Job? = null
private val timeMillis = MutableLiveData("00:00:00")
private val _started = MutableLiveData(false)
val started: LiveData<Boolean> = _started
val time = timeMillis
private val sdf = SimpleDateFormat("hh:mm:ss:SS", Locale.US)
fun startOrPause() {
if (_started.value == true) {
_started.value = false
job?.cancel()
} else {
_started.value = true
job = viewModelScope.launch { start() }
}
}
private suspend fun CoroutineScope.start() {
while (isActive) {
timeMillis.value = sdf.format(Date())
awaitFrame()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment