Hello I had spend over 10 hour to implement Combine
framework but can't clear understanding how to link Publisher
and Subscriber
. In example I just wanna call setTheme
funk from Theme
class and automatically update game
variable in Game
class. I know how to achieve it with didSet
but main goal to make it with Combine
. Would be thankfull for help.
import SwiftUI
import Combine
import Foundation
class Theme: ObservableObject {
@Published private(set) var choosenTheme: Color? // Publisher right?
func setTheme(with color: Color?) {
if let unwrappedColor = color {
self.choosenTheme = unwrappedColor
} else {
self.choosenTheme = nil
}
}
}
class Game: ObservableObject {
@Published var game: String? // Subscriber right?
private let gameTheme = Theme()
private var cancellables = Set<AnyCancellable>()
init() {
addSubscribers()
}
private func addSubscribers() { // I think something wrong here
gameTheme.$choosenTheme
.map(createGame)
.sink { [weak self] (returnedString) in
print("Value from sink \(String(describing: returnedString))")
self?.game = returnedString
}
.store(in: &cancellables)
}
private func createGame(for theme: Color?) -> String? {
if let unwrappedTheme = theme {
print(unwrappedTheme)
return String("\(unwrappedTheme)")
} else {
return nil
}
}
}
// Test:
var testTheme = Theme()
testTheme.setTheme(with: .orange)
var testGame = Game()
print(testGame.game) // Should be Orange
testTheme.setTheme(with: .blue)
print(testGame.game) // Should be Blue
testTheme.setTheme(with: nil)
print(testGame.game) // Should be nil