Skip to content

Instantly share code, notes, and snippets.

@Arunshaik2001
Created January 21, 2023 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Arunshaik2001/fdc3e912b0d16759190a7ada67204769 to your computer and use it in GitHub Desktop.
Save Arunshaik2001/fdc3e912b0d16759190a7ada67204769 to your computer and use it in GitHub Desktop.
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