Created
July 7, 2023 14:15
-
-
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
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
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