waitUntilValueIs.kt 664 B

123456789101112131415161718192021222324
  1. package com.example.modifier.extension
  2. import androidx.lifecycle.MutableLiveData
  3. import androidx.lifecycle.Observer
  4. import kotlinx.coroutines.suspendCancellableCoroutine
  5. import kotlin.coroutines.resume
  6. suspend fun <T> MutableLiveData<T>.waitUntilValueIs(expectedValue: T) {
  7. if (this.value == expectedValue) return
  8. suspendCancellableCoroutine<Unit> { continuation ->
  9. val observer = Observer<T> { value ->
  10. if (value == expectedValue) {
  11. continuation.resume(Unit)
  12. }
  13. }
  14. observeForever(observer)
  15. continuation.invokeOnCancellation {
  16. removeObserver(observer)
  17. }
  18. }
  19. }