Last active
July 8, 2021 09:23
-
-
Save mrahimygk/b73812b5ecad00903b5c9e6f0214467d 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
class GithubSearchViewModel( | |
private val searchGithubUseCase: SearchGithubUseCase, | |
private val likeGithubUseCase: LikeGithubRepoUseCase | |
) : BaseViewModel(), EmptyObservableHost { | |
val shouldClearCurrentSearchResults = false | |
private val searchEvent: MediatorLiveData<String?> = searchQuery.map { | |
if (it.isNullOrBlank() || (restoredSearchQuery != null && restoredSearchQuery == it)) null | |
else { | |
pageNumber = 1 | |
shouldClearCurrentSearchResults = true | |
it.trim() | |
} | |
}.debounce(SEARCH_DEBOUNCE_TIME, viewModelScope) | |
val dataList: LiveData<List<GithubQuery>> = searchResult.map { | |
when (it) { | |
is ApiResult.Success -> { | |
mIsInPullToRefreshState.postValue(false) | |
if (pageNumber == 1) { | |
_onSuccessfulFirstPageFetch.postValue(Any()) | |
} | |
if (it.data.items.isNotEmpty()) { | |
pageNumber += 1 | |
} | |
/** | |
* Every time users update [searchQuery], they need a fresh search result. | |
* so if the [searchResult] are coming from a new searched query and not a pagination call, | |
* we clear the current list of items. | |
*/ | |
if (shouldClearCurrentSearchResults) { | |
currentGithubQueryList.clear() | |
} | |
currentGithubQueryList.addAll(it.data.items) | |
return@map currentGithubQueryList | |
} | |
} | |
} | |
fun onCardsReachTheEnd() { | |
shouldClearCurrentSearchResults = false | |
searchByExistingValues(true) | |
} | |
fun onCardsReachingTheEnd() { | |
shouldClearCurrentSearchResults = false | |
searchByExistingValues(true) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment