Created
March 30, 2020 10:50
-
-
Save mig35/c8581e8d6cff3cf398b324366e0c0b16 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
internal class ChangeFavoriteStatusCommand( | |
private val mainItemUid: String, | |
private val changeToFavorite: Boolean, | |
private val changeFavoriteAction: suspend () -> Unit, | |
private val onFavoriteChangeFailed: (Throwable) -> Unit | |
) : ActionCommandWithStrategy<Unit, ListScreenState>(ConcurrentStrategyWithTag(mainItemUid)) { | |
override fun onCommandWasAdded(dataState: ListScreenState): ListScreenState = | |
// we update item state only if the list contains this item | |
if (dataState.pageData?.itemsList?.any { it.key == mainItemUid } == true) { | |
dataState.copy( | |
pageData = dataState.pageData?.updateItemFavoriteState { | |
it.newSelection(changeToFavorite) | |
} | |
) | |
} else { | |
dataState | |
} | |
override suspend fun executeCommand(dataState: ListScreenState) { | |
val uiMainItem = dataState.pageData?.itemsList?.firstOrNull { it.key == mainItemUid } | |
if (uiMainItem?.favoriteState is FavoriteState.PreSelectProgress && uiMainItem.favoriteState.hasChange()) { | |
// we should run this command only if there was a change. otherwise we should skip it | |
changeFavoriteAction() | |
} | |
} | |
override fun onExecuteSuccess(dataState: ListScreenState, result: Unit): ListScreenState = | |
if (dataState.pageData?.itemsList?.any { it.key == mainItemUid } == true) { | |
dataState.copy( | |
pageData = dataState.pageData?.updateItemFavoriteState { | |
it.newFinalState(changeToFavorite) | |
} | |
) | |
} else { | |
dataState | |
} | |
override fun onExecuteFail(dataState: ListScreenState, error: Throwable): ListScreenState = | |
if (dataState.pageData?.itemsList?.any { it.key == mainItemUid } == true) { | |
var hasChange = false | |
val newData = dataState.copy( | |
pageData = dataState.pageData?.updateItemFavoriteState { | |
val newFavoriteState = it.revertState(!changeToFavorite) | |
if (it.favorite != newFavoriteState.favorite) { | |
hasChange = true | |
} | |
newFavoriteState | |
} | |
) | |
if (hasChange) onFavoriteChangeFailed(error) | |
newData | |
} else { | |
dataState | |
} | |
private fun PageDataWithNextPageNumber<UIMainItem>.updateItemFavoriteState( | |
newStateGenerator: (FavoriteState) -> FavoriteState | |
): PageDataWithNextPageNumber<UIMainItem> = | |
PageDataWithNextPageNumber( | |
itemsList.map { | |
if (it.key == mainItemUid) | |
it.copy(favoriteState = newStateGenerator(it.favoriteState)) | |
else | |
it | |
}, | |
nextPageNumber | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment