Last active
April 2, 2020 07:05
-
-
Save mig35/32876c52c99d234249bb46b4b9196a85 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
class SimpleListViewModel(application: Application) : ListViewModel(application) { | |
private val mutableScreenState = MutableLiveData( | |
ListScreenState(null, null, null) | |
) | |
override val screenState: LiveData<ListScreenState> = mutableScreenState | |
override val commandManager: CommandManager<ListScreenState> by lazy { | |
CommandManagerImpl(mutableScreenState, viewModelScope) | |
} | |
init { | |
reload() | |
} | |
override fun reload() { | |
commandManager.postCommand( | |
RefreshCommand( | |
{ executeLoadNextPage(0) }, | |
{ UIProgressErrorItem.Progress }, | |
{ UIProgressErrorItem.Error(it.toString()) { reload() } } | |
) | |
) | |
} | |
override fun loadNextPage() { | |
commandManager.postCommand( | |
LoadNextWithPageNumberCommand( | |
{ executeLoadNextPage(it) }, | |
{ UIProgressErrorItem.Progress }, | |
{ UIProgressErrorItem.Error(it.toString()) { loadNextPage() } } | |
) | |
) | |
} | |
private suspend fun executeLoadNextPage(pageNumber: Int): PageDataWithNextPageNumber<UIMainItem> { | |
val items = | |
withContext(Dispatchers.IO) { | |
HardCodeRepository.loadNextMainPage(pageNumber, PAGE_SIZE) | |
} | |
return PageDataWithNextPageNumber( | |
withContext(Dispatchers.Default) { items.map { it.toUIMainItem() } }, | |
if (items.isEmpty()) null else pageNumber + 1 | |
) | |
} | |
override fun removeFromFavorite(item: UIMainItem) { | |
if (item.favoriteState.favorite) { | |
executeFavoriteChangeAction(item.uid, false) | |
} | |
} | |
override fun addToFavorite(item: UIMainItem) { | |
if (!item.favoriteState.favorite) { | |
executeFavoriteChangeAction(item.uid, true) | |
} | |
} | |
private fun executeFavoriteChangeAction(uid: String, newFavoriteStatus: Boolean) { | |
commandManager.postCommand( | |
ChangeFavoriteStatusCommand( | |
uid, | |
newFavoriteStatus, | |
{ | |
withContext(Dispatchers.IO) { | |
HardCodeRepository.changeFavoriteStatus(uid, newFavoriteStatus) | |
} | |
}, | |
{ Toast.makeText(getApplication(), it.toString(), Toast.LENGTH_SHORT).show() } | |
) | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment