Skip to content

Commit

Permalink
Update BalanceViewModel to use @published state
Browse files Browse the repository at this point in the history
  • Loading branch information
cicerocamargo committed May 16, 2021
1 parent 752a7f9 commit cd9dbd1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 19 deletions.
20 changes: 10 additions & 10 deletions CombineIntro/BalanceFeature/BalanceViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ class BalanceViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

viewModel.statePublisher
.sink { [weak self] _ in self?.updateView() }
viewModel.$state
.sink { [weak self] in self?.updateView(state: $0) }
.store(in: &cancellables)

rootView.refreshButton.touchUpInsidePublisher
Expand All @@ -43,20 +43,20 @@ class BalanceViewController: UIViewController {
viewModel.refreshBalance()
}

private func updateView() {
rootView.refreshButton.isHidden = viewModel.state.isRefreshing
if viewModel.state.isRefreshing {
private func updateView(state: BalanceViewState) {
rootView.refreshButton.isHidden = state.isRefreshing
if state.isRefreshing {
rootView.activityIndicator.startAnimating()
} else {
rootView.activityIndicator.stopAnimating()
}
rootView.valueLabel.text = viewModel.state.formattedBalance
rootView.valueLabel.alpha = viewModel.state.isRedacted
rootView.valueLabel.text = state.formattedBalance
rootView.valueLabel.alpha = state.isRedacted
? BalanceView.alphaForRedactedValueLabel
: 1
rootView.infoLabel.text = viewModel.state.infoText(formatDate: formatDate)
rootView.infoLabel.textColor = viewModel.state.infoColor
rootView.redactedOverlay.isHidden = !viewModel.state.isRedacted
rootView.infoLabel.text = state.infoText(formatDate: formatDate)
rootView.infoLabel.textColor = state.infoColor
rootView.redactedOverlay.isHidden = !state.isRedacted

view.setNeedsLayout()
}
Expand Down
11 changes: 2 additions & 9 deletions CombineIntro/BalanceFeature/BalanceViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,13 @@ import Foundation
import UIKit

final class BalanceViewModel {
private let stateSubject: CurrentValueSubject<BalanceViewState, Never>
private(set) var state: BalanceViewState {
get { stateSubject.value }
set { stateSubject.send(newValue) }
}
var statePublisher: AnyPublisher<BalanceViewState, Never> {
stateSubject.eraseToAnyPublisher()
}
@Published private(set) var state = BalanceViewState()

private let service: BalanceService
private var cancellables: Set<AnyCancellable> = []

init(service: BalanceService) {
self.service = service
stateSubject = .init(BalanceViewState())

NotificationCenter.default
.publisher(for: UIApplication.willResignActiveNotification)
Expand Down

0 comments on commit cd9dbd1

Please sign in to comment.