-
-
Save Arunshaik2001/fdc3e912b0d16759190a7ada67204769 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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