@@ -12,6 +12,55 @@ import Foundation
1212/// Multiple observers are allowed which makes this a possible replacement for
1313/// `NSNotificationCenter` observations.
1414///
15+ /// ## Example Usage
16+ ///
17+ /// In a class that you would like to emit values (or events), add the `PublishSubject` defining
18+ /// the value type:
19+ ///
20+ /// ```
21+ /// class PostListViewModel {
22+ /// /// Calls observers/subscribers whenever the list of Post changes.
23+ /// private let postsSubject = PublishSubject<[Post]>()
24+ /// }
25+ /// ```
26+ ///
27+ /// Since `PublishSubject` exposes `send()` which makes this a **mutable** Observable, we recommend
28+ /// exposing only the `Observable<[Post]>` interface:
29+ ///
30+ /// ```
31+ /// class PostListViewModel {
32+ /// private let postsSubject = PublishSubject<[Post]>()
33+ ///
34+ /// /// The public Observable that the ViewController will subscribe to
35+ /// var posts: Observable<[Post]> {
36+ /// postsSubject
37+ /// }
38+ /// }
39+ /// ```
40+ ///
41+ /// The `ViewController` can then subscribe to the `posts` Observable:
42+ ///
43+ /// ```
44+ /// func viewDidLoad() {
45+ /// viewModel.posts.subscribe { posts in
46+ /// // do something with posts
47+ /// tableView.reloadData()
48+ /// }
49+ /// }
50+ /// ```
51+ ///
52+ /// Whenever the list of post changes, like after fetching from the API, the `ViewModel` can
53+ /// _notify_ the `ViewController` by updating `postsSubject`:
54+ ///
55+ /// ```
56+ /// fetchFromAPI { fetchedPosts
57+ /// // Notify the observers (e.g. ViewController) that the list of posts have changed
58+ /// postsSubject.send(fetchedPosts)
59+ /// }
60+ /// ```
61+ ///
62+ /// ## References
63+ ///
1564/// See here for info about similar observables in other frameworks:
1665///
1766/// - https://developer.apple.com/documentation/combine/passthroughsubject
0 commit comments