Skip to content

Instantly share code, notes, and snippets.

@MRezaNasirloo
Last active April 3, 2021 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MRezaNasirloo/f75f8c2d784b1ffd1586958f1cec139e to your computer and use it in GitHub Desktop.
Save MRezaNasirloo/f75f8c2d784b1ffd1586958f1cec139e to your computer and use it in GitHub Desktop.
An Either class
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