Last active
May 19, 2020 14:09
-
-
Save psteiger/d5df0a73f03354379f35cf50dc08699b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Resource<out T> { | |
| data class Success<out T>(val data: T) : Resource<T>() | |
| data class Loading<out T>(val partialData: T? = null) : Resource<T>() | |
| data class Failure<out T>(val throwable: Throwable? = null) : Resource<T>() | |
| val extractData: T? get() = when (this) { | |
| is Success -> data | |
| is Loading -> partialData | |
| is Failure -> null | |
| } | |
| inline fun <Y> mapResource(crossinline transform: (T) -> Y): Resource<Y> = try { | |
| when (this) { | |
| is Success<T> -> Success<Y>(transform(data)) | |
| is Loading<T> -> Loading<Y>(partialData?.let { transform(it) }) | |
| is Failure<T> -> Failure<Y>(throwable) | |
| } | |
| } catch (e: Throwable) { | |
| Resource.Failure<Y>(e) | |
| } | |
| fun onSuccess(onSuccess: (data: T) -> Unit): Resource<T> { | |
| if (this is Success) | |
| onSuccess(data) | |
| return this | |
| } | |
| fun onLoading(onLoading: (partialData: T?) -> Unit): Resource<T> { | |
| if (this is Loading) | |
| onLoading(partialData) | |
| return this | |
| } | |
| fun onFailure(onFailure: (throwable: Throwable?) -> Unit): Resource<T> { | |
| if (this is Failure) | |
| onFailure(throwable) | |
| return this | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment