package com.example.modifier.extension

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

suspend fun <T> MutableLiveData<T>.waitUntilValueIs(expectedValue: T) {
    if (this.value == expectedValue) return

    suspendCancellableCoroutine<Unit> { continuation ->
        val observer = Observer<T> { value ->
            if (value == expectedValue) {
                continuation.resume(Unit)
            }
        }

        observeForever(observer)

        continuation.invokeOnCancellation {
            removeObserver(observer)
        }
    }
}