Refactor LiveData extensions

This commit is contained in:
Koitharu
2022-07-13 15:58:20 +03:00
parent 29c82177a9
commit 4607e5ba0f
9 changed files with 21 additions and 61 deletions

View File

@@ -2,7 +2,6 @@ package org.koitharu.kotatsu.utils.ext
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.liveData
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
@@ -10,14 +9,6 @@ import org.koitharu.kotatsu.utils.BufferedObserver
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
fun <T> LiveData<T?>.observeNotNull(owner: LifecycleOwner, observer: Observer<T>) {
this.observe(owner) {
if (it != null) {
observer.onChanged(it)
}
}
}
fun <T> LiveData<T>.requireValue(): T = checkNotNull(value) {
"LiveData value is null"
}
@@ -30,17 +21,6 @@ fun <T> LiveData<T>.observeWithPrevious(owner: LifecycleOwner, observer: Buffere
}
}
@Deprecated("Use variant with default value")
fun <T> Flow<T>.asLiveDataDistinct(
context: CoroutineContext = EmptyCoroutineContext
): LiveData<T> = liveData(context) {
collect {
if (it != latestValue) {
emit(it)
}
}
}
fun <T> StateFlow<T>.asLiveDataDistinct(
context: CoroutineContext = EmptyCoroutineContext
): LiveData<T> = asLiveDataDistinct(context, value)
@@ -48,7 +28,7 @@ fun <T> StateFlow<T>.asLiveDataDistinct(
fun <T> Flow<T>.asLiveDataDistinct(
context: CoroutineContext = EmptyCoroutineContext,
defaultValue: T
): LiveData<T> = liveData(context, 0L) {
): LiveData<T> = liveData(context) {
if (latestValue == null) {
emit(defaultValue)
}
@@ -57,18 +37,4 @@ fun <T> Flow<T>.asLiveDataDistinct(
emit(it)
}
}
}
fun <T> Flow<T>.asLiveDataDistinct(
context: CoroutineContext = EmptyCoroutineContext,
defaultValue: suspend () -> T
): LiveData<T> = liveData(context) {
if (latestValue == null) {
emit(defaultValue())
}
collect {
if (it != latestValue) {
emit(it)
}
}
}