Last active
April 3, 2021 07:55
-
-
Save MRezaNasirloo/f75f8c2d784b1ffd1586958f1cec139e to your computer and use it in GitHub Desktop.
An Either class
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
sealed class Either<L> { | |
class Success<L>(val value: L) : Either<L>() | |
class Error<L>(val title: String, val message: String) : Either<L>() | |
fun success(success: L.() -> Unit) { | |
if (this is Success<L>) success(value) | |
} | |
fun error(error: (Error<L>).() -> Unit) { | |
if (this is Error<L>) error(this) | |
} | |
} | |
inline fun <T> LiveData<T>.observeEither( | |
owner: LifecycleOwner, | |
crossinline either: T.() -> Unit | |
) { | |
observeNullSafe(owner, either) | |
} | |
inline fun <T> LiveData<T>.observeNullSafe( | |
owner: LifecycleOwner, | |
crossinline observer: (T) -> Unit | |
) { | |
observe(owner, Observer { nullableValue -> | |
nullableValue?.also { | |
observer(it) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment