Skip to content

Instantly share code, notes, and snippets.

@kaszabimre
Created July 7, 2023 14:15
Show Gist options
  • Save kaszabimre/225463deb16153adf467e0c1e847f6e3 to your computer and use it in GitHub Desktop.
Save kaszabimre/225463deb16153adf467e0c1e847f6e3 to your computer and use it in GitHub Desktop.
The ReducerViewModel class wraps the state of KMM ViewModels into Combine's Published properties, enabling reactive programming and data binding on the iOS platform. V2
import shared
import Combine
@MainActor
final class ReducerViewModel<S, V>: ObservableObject where S: UiState, V: ViewModel, V: StateFlowAdaptable {
@LazyKoin var viewModel: V
@Published public var state: S?
@Published public var error: String?
private var cancellables = Set<AnyCancellable>()
init() {
doPublish(viewModel.stateFlowAdapter) { [weak self] in
self?.state = $0 as? S
}
.store(in: &cancellables)
doPublish(viewModel.errorFlowAdapter) { [weak self] in
if let error = $0 as? String {
self?.error = String(error)
} else {
self?.error = nil
}
}
.store(in: &cancellables)
}
func deactivate() {
viewModel.clear()
cancellables.removeAll()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment