Creating an observable class in iOS using the latest APIs involves leveraging Swift's modern concurrency features, such as Combine (for reactive programming) or async/await (for structured concurrency). The most common and recommended approach for creating observable classes in iOS is to use the Combine framework, which integrates seamlessly with SwiftUI and UIKit. Below, I'll walk you through how to properly create an observable class using Combine and @Published properties, and I'll also touch on alternatives using async/await for specific use cases.
1. Using Combine to Create an Observable Class
The Combine framework provides a declarative way to handle asynchronous events and data streams. To create an observable class, you typically use the @Published property wrapper and conform to the ObservableObject protocol. This is particularly useful for SwiftUI applications, but it can also be used with UIKit.
Step-by-Step Guide
-
Import Combine Framework
Ensure you import the Combine framework in your file.
-
Conform to ObservableObject
Make your class conform to the ObservableObject protocol. This protocol allows instances of your class to be observed for changes.
-
Use @Published for Observable Properties
Use the @Published property wrapper to mark properties that should trigger updates to observers when their values change.
-
Observe Changes
Use Combine's sink or SwiftUI's @StateObject/@ObservedObject to observe changes to the class.
Example: Observable Class with Combine
import Combine
class UserViewModel: ObservableObject {
// @Published properties are automatically observable
@Published var username: String = ""
@Published var isLoggedIn: Bool = false
// A set to store cancellable subscriptions
private var cancellables = Set<AnyCancellable>()
init() {
// Example: React to changes in username
$username
.sink { newUsername in
print("Username changed to: \(newUsername)")
}
.store(in: &cancellables)
}
// Example method to update the state
func login() {
isLoggedIn = true
username = "JohnDoe"
}
func logout() {
isLoggedIn = false
username = ""
}
}
How to Use the Observable Class
- In SwiftUI: Use
@StateObject or @ObservedObject to observe changes to the class in a SwiftUI view.
import SwiftUI
struct ContentView: View {
@StateObject private var viewModel = UserViewModel()
var body: some View {
VStack {
Text("Username: \(viewModel.username)")
Text("Logged In: \(viewModel.isLoggedIn ? "Yes" : "No")")
Button("Login") {
viewModel.login()
}
Button("Logout") {
viewModel.logout()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
- In UIKit: Use Combine's
sink to subscribe to changes in the observable properties.
import UIKit
import Combine
class ViewController: UIViewController {
private var viewModel = UserViewModel()
private var cancellables = Set<AnyCancellable>()
override func viewDidLoad() {
super.viewDidLoad()
// Subscribe to changes in isLoggedIn
viewModel.$isLoggedIn
.sink { [weak self] isLoggedIn in
self?.updateUI(isLoggedIn: isLoggedIn)
}
.store(in: &cancellables)
}
private func updateUI(isLoggedIn: Bool) {
print("User is logged in: \(isLoggedIn)")
}
}
2. Key Points About Combine-Based Observable Classes
@Published: Automatically creates a Publisher for the property, which emits values whenever the property changes.
ObservableObject: Provides an objectWillChange publisher that notifies observers before any @Published property changes.
- Memory Management: Use
cancellables to store subscriptions and prevent memory leaks. The store(in:) method ensures that subscriptions are automatically cleaned up when the cancellable set is deallocated.
- Threading: Combine publishers are thread-safe, but ensure that UI updates are performed on the main thread (e.g., using
.receive(on: DispatchQueue.main)).
3. Alternative: Using async/await for Observability
If you're working with iOS 15+ and prefer structured concurrency over Combine, you can use AsyncStream to create an observable data stream. This approach is more manual and doesn't integrate as seamlessly with SwiftUI, but it can be useful for specific use cases, such as observing asynchronous events or data sources.
Example: Observable Class with AsyncStream
import Foundation
class SensorDataModel {
private var temperature: Double = 0.0
// Create an AsyncStream to observe temperature changes
var temperatureStream: AsyncStream<Double> {
AsyncStream { continuation in
// Simulate temperature updates
Task {
while true {
try await Task.sleep(nanoseconds: 1_000_000_000) // 1 second delay
temperature += 1.0
continuation.yield(temperature)
}
}
}
}
// Method to manually update temperature
func updateTemperature(_ newValue: Double) {
temperature = newValue
}
}
// Usage example
Task {
let sensorModel = SensorDataModel()
for await temp in sensorModel.temperatureStream {
print("Temperature updated: \(temp)")
}
}
Key Points About AsyncStream
AsyncStream: Provides a way to create a stream of values that can be consumed using for await.
- Manual Updates: Unlike Combine's
@Published, you need to manually call continuation.yield to emit new values.
- Use Case: This approach is better suited for scenarios where you're dealing with asynchronous data sources (e.g., network requests, sensors) rather than simple state changes.
4. Best Practices for Observable Classes
- Use Combine for SwiftUI: If you're building a SwiftUI app, use
ObservableObject and @Published for the best integration and performance.
- Minimize State: Only mark properties as
@Published if they need to be observed. Unnecessary publishers can lead to performance overhead.
- Thread Safety: Ensure UI updates are performed on the main thread. Combine provides
.receive(on:) for this purpose.
- Memory Management: Always store Combine subscriptions in a
Set<AnyCancellable> to avoid memory leaks.
- Consider
async/await for Async Work: If your observable class involves asynchronous operations (e.g., network requests), consider using async/await with AsyncStream or Combine's Future.
- Testability: Make your observable class testable by injecting dependencies and mocking publishers.
5. Advanced Example: Combining Combine and Async/Await
For modern iOS apps, you might want to combine Combine and async/await for a more flexible observable class. Here's an example that fetches data asynchronously and publishes it using Combine:
import Combine
import Foundation
class DataViewModel: ObservableObject {
@Published var data: String = "Loading..."
@Published var error: Error?
private var cancellables = Set<AnyCancellable>()
func fetchData() {
Task {
do {
let fetchedData = try await fetchDataAsync()
await MainActor.run {
self.data = fetchedData
}
} catch {
await MainActor.run {
self.error = error
}
}
}
}
private func fetchDataAsync() async throws -> String {
// Simulate an async network request
try await Task.sleep(nanoseconds: 2_000_000_000) // 2 seconds
return "Fetched Data"
}
}
// Usage in SwiftUI
struct DataView: View {
@StateObject private var viewModel = DataViewModel()
var body: some View {
VStack {
Text(viewModel.data)
if let error = viewModel.error {
Text("Error: \(error.localizedDescription)")
}
Button("Fetch Data") {
viewModel.fetchData()
}
}
}
}
6. Conclusion
- For SwiftUI Apps: Use
ObservableObject and @Published with Combine for the simplest and most integrated solution.
- For UIKit Apps: Use Combine publishers and subscribers, ensuring proper memory management with
cancellables.
- For Async Work: Consider
async/await with AsyncStream for custom asynchronous data streams, or combine it with Combine for publishing results.
- Stay Up-to-Date: Always use the latest iOS APIs (e.g., iOS 15+ features like
async/await) to ensure your code is modern and maintainable.
By following these guidelines, you'll create robust, observable classes that work seamlessly with modern iOS development practices.