Created
July 1, 2017 16:36
-
-
Save toyamah/8884ad4a71a4959018dbd44b374ed48e to your computer and use it in GitHub Desktop.
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
fun Observable<Int>.foo(userApp: UserAppService): Pair<Observable<UiModel>, Observable<Boolean>> { | |
val shouldShowLoading = BehaviorSubject.createDefault<Boolean>(false).toSerialized() | |
var isLoading = false | |
var hasLoaded = false | |
var page = 1 | |
val uiModel = this | |
.filter { !hasLoaded && !isLoading } | |
.doOnNext { _ -> | |
isLoading = true | |
if (page != 1) shouldShowLoading.onNext(true) | |
} | |
.flatMap( | |
{ _ -> | |
userApp.getAllUsers(++page, 20) | |
.doOnEach { shouldShowLoading.onNext(false) } | |
.delay(2, TimeUnit.SECONDS) | |
.subscribeOnIo() | |
.observeOnMain() | |
}, | |
{ t1, t2 -> page to t2 }) | |
.doOnNext { (page, _) -> | |
isLoading = false | |
if (page != 1) shouldShowLoading.onNext(false) | |
} | |
.map { (page, userList) -> | |
if (userList.isEmpty()) { | |
hasLoaded = true | |
} | |
if (page == 1 && userList.isEmpty()) { | |
EmptyModel | |
} else { | |
DataModel(userList, userList.isEmpty()) | |
} | |
} | |
.onErrorReturn { ErrorModel } | |
.startWith(LoadingModel) | |
return uiModel to shouldShowLoading.hide() | |
} | |
sealed class UiModel | |
object EmptyModel : UiModel() | |
object ErrorModel : UiModel() | |
object LoadingModel : UiModel() | |
data class DataModel(val data: List<User>, val hasLoaded: Boolean) : UiModel() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment