Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hlung/4f6b35b61eda6dae93454f3b9ab2b1d4 to your computer and use it in GitHub Desktop.
Save hlung/4f6b35b61eda6dae93454f3b9ab2b1d4 to your computer and use it in GitHub Desktop.
func perform(followAction: FollowAction,
cache: Cache<FanClub>,
updateHandler: @escaping (_ isRevertOnFailure: Bool) -> Void) {
// update cache optimistically
let originalFanClub = cache.value(for: followAction.fanClubId)
if let updatedFanClub = originalFanClub?.updated(with: followAction) {
cache.set(updatedFanClub, for: followAction.fanClubId)
}
updateHandler(false)
lastFollowActionUpdatedAt = Date()
// send network request
apiClient.followFanClub(id: followAction.fanClubId, isOn: followAction.isOn)
.observeOn(MainScheduler.instance)
.subscribe(onCompleted: nil, onError: { [weak self] error in
guard let weakSelf = self else { return }
weakSelf.delegate?.actionController(weakSelf, didReceive: error)
// revert on failure
if let originalFanClub = originalFanClub {
cache.set(originalFanClub, for: followAction.fanClubId)
}
updateHandler(true)
})
.disposed(by: disposeBag)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment