-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathextending-creating-publishers-the-right-way.html
377 lines (327 loc) · 17 KB
/
extending-creating-publishers-the-right-way.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://use.fontawesome.com/afd448ce82.js"></script>
<!-- Meta Tag -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- SEO -->
<meta name="author" content="Bruno Rocha">
<meta name="keywords" content="Software, Engineering, Blog, Posts, iOS, Xcode, Swift, Articles, Tutorials, OBJ-C, Objective-C, Apple">
<meta name="description" content="In this article, I'll show you how to properly extend existing publishers and how to wrap them when creating your own custom publishers.">
<meta name="title" content="Extending / Creating Combine Publishers the Right Way">
<meta name="url" content="https://swiftrocks.com/extending-creating-publishers-the-right-way">
<meta name="image" content="https://swiftrocks.com/images/thumbs/thumb.jpg?4">
<meta name="copyright" content="Bruno Rocha">
<meta name="robots" content="index,follow">
<meta property="og:title" content="Extending / Creating Combine Publishers the Right Way"/>
<meta property="og:image" content="https://swiftrocks.com/images/thumbs/thumb.jpg?4"/>
<meta property="og:description" content="In this article, I'll show you how to properly extend existing publishers and how to wrap them when creating your own custom publishers."/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="https://swiftrocks.com/extending-creating-publishers-the-right-way"/>
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://swiftrocks.com/images/thumbs/thumb.jpg?4"/>
<meta name="twitter:image:alt" content="Page Thumbnail"/>
<meta name="twitter:title" content="Extending / Creating Combine Publishers the Right Way"/>
<meta name="twitter:description" content="In this article, I'll show you how to properly extend existing publishers and how to wrap them when creating your own custom publishers."/>
<meta name="twitter:site" content="@rockbruno_"/>
<!-- Favicon -->
<link rel="icon" type="image/png" href="images/favicon/iconsmall2.png" sizes="32x32" />
<link rel="apple-touch-icon" href="images/favicon/iconsmall2.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Sans+3:ital,wght@0,200..900;1,200..900&display=swap" rel="stylesheet">
<link rel="canonical" href="https://swiftrocks.com/extending-creating-publishers-the-right-way"/>
<!-- Bootstrap CSS Plugins -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<!-- Prism CSS Stylesheet -->
<link rel="stylesheet" type="text/css" href="css/prism4.css">
<!-- Main CSS Stylesheet -->
<link rel="stylesheet" type="text/css" href="css/style48.css">
<link rel="stylesheet" type="text/css" href="css/sponsor4.css">
<!-- HTML5 shiv and Respond.js support IE8 or Older for HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "BlogPosting",
"mainEntityOfPage": {
"@type": "WebPage",
"@id": "https://swiftrocks.com/extending-creating-publishers-the-right-way"
},
"image": [
"https://swiftrocks.com/images/thumbs/thumb.jpg"
],
"datePublished": "2021-07-27T14:00:00+02:00",
"dateModified": "2021-07-27T14:00:00+02:00",
"author": {
"@type": "Person",
"name": "Bruno Rocha"
},
"publisher": {
"@type": "Organization",
"name": "SwiftRocks",
"logo": {
"@type": "ImageObject",
"url": "https://swiftrocks.com/images/thumbs/thumb.jpg"
}
},
"headline": "Extending / Creating Combine Publishers the Right Way",
"abstract": "In this article, I'll show you how to properly extend existing publishers and how to wrap them when creating your own custom publishers."
}
</script>
</head>
<body>
<div id="main">
<!-- Blog Header -->
<!-- Blog Post (Right Sidebar) Start -->
<div class="container">
<div class="col-xs-12">
<div class="page-body">
<div class="row">
<div><a href="https://swiftrocks.com">
<img id="logo" class="logo" alt="SwiftRocks" src="images/bg/logo2light.png">
</a>
<div class="menu-large">
<div class="menu-arrow-right"></div>
<div class="menu-header menu-header-large">
<div class="menu-item">
<a href="blog">blog</a>
</div>
<div class="menu-item">
<a href="about">about</a>
</div>
<div class="menu-item">
<a href="talks">talks</a>
</div>
<div class="menu-item">
<a href="projects">projects</a>
</div>
<div class="menu-item">
<a href="software-engineering-book-recommendations">book recs</a>
</div>
<div class="menu-item">
<a href="games">game recs</a>
</div>
<div class="menu-arrow-right-2"></div>
</div>
</div>
<div class="menu-small">
<div class="menu-arrow-right"></div>
<div class="menu-header menu-header-small-1">
<div class="menu-item">
<a href="blog">blog</a>
</div>
<div class="menu-item">
<a href="about">about</a>
</div>
<div class="menu-item">
<a href="talks">talks</a>
</div>
<div class="menu-item">
<a href="projects">projects</a>
</div>
<div class="menu-arrow-right-2"></div>
</div>
<div class="menu-arrow-right"></div>
<div class="menu-header menu-header-small-2">
<div class="menu-item">
<a href="software-engineering-book-recommendations">book recs</a>
</div>
<div class="menu-item">
<a href="games">game recs</a>
</div>
<div class="menu-arrow-right-2"></div>
</div>
</div>
</div>
<div class="content-page" id="WRITEIT_DYNAMIC_CONTENT">
<!--WRITEIT_POST_NAME=Extending / Creating Combine Publishers the Right Way-->
<!--WRITEIT_POST_HTML_NAME=extending-creating-publishers-the-right-way-->
<!--Add here the additional properties that you want each page to possess.-->
<!--These properties can be used to change content in the template page or in the page itself as shown here.-->
<!--Properties must start with 'WRITEIT_POST'.-->
<!--Writeit provides and injects WRITEIT_POST_NAME and WRITEIT_POST_HTML_NAME by default.-->
<!--WRITEIT_POST_SHORT_DESCRIPTION=In this article, I'll show you how to properly extend existing publishers and how to wrap them when creating your own custom publishers.-->
<!--DateFormat example: 2021-07-27T14:00:00+02:00-->
<!--WRITEIT_POST_SITEMAP_DATE_LAST_MOD=2021-07-27T14:00:00+02:00-->
<!--WRITEIT_POST_SITEMAP_DATE=2021-07-27T14:00:00+02:00-->
<title>Extending / Creating Combine Publishers the Right Way</title>
<div class="blog-post">
<div class="post-title-index">
<h1>Extending / Creating Combine Publishers the Right Way</h1>
</div>
<div class="post-info">
<div class="post-info-text">
Published on 26 Jul 2021
</div>
</div>
<p>I've been playing around with <b>Combine</b> for a while now and had some trouble navigating all the new protocols and types, especially when it came to extensions. In this article, I'll show you how to properly extend existing publishers and how to wrap them when creating your own custom publishers.</p>
<div class="sponsor-article-ad-auto hidden"></div>
<h2>The Easy Case: Extending Basic Output Publishers</h2>
<p>One of my favorite uses of Combine is how easily composable everything is. There's no need to create custom classes unless you really need to keep track of an external object:</p>
<pre><code>let publisher = CurrentValueSubject<Int, Never>(0)
let evenSquaredPublisher = publisher.filter {
$0 % 2 == 0
}.map {
$0 * $0
}
let cancellable = evenSquaredPublisher.sink { print($0) }</code></pre>
<p>Since all articles require a non-sense example, our example is going to be a publisher that streams the squared of even numbers. As you can see, it's trivial to develop this functionality, but what if we wanted to do this more than once around our code?</p>
<p>Surprisingly, due to limitations on the constrained extensions API, it took me a while to figure out the right way to abstract this under a function. My first idea, and what I think some people out there are doing, is to extend <code>AnyPublisher</code> and constrain it to the <code>Int</code> output used by the example:</p>
<pre><code>extension AnyPublisher where Output == Int {
func evenSquared() -> AnyPublisher<Output, Failure> {
return filter {
$0 % 2 == 0
}.map {
$0 * $0
}.eraseToAnyPublisher()
}
}</code></pre>
<p>This however is not the right approach, because you'll now have to erase everyone who wants to use this method, and that's not why <code>AnyPublisher</code> exists:</p>
<pre><code>let evenSquaredPublisher = publisher.eraseToAnyPublisher().evenSquared()</code></pre>
<p>To extend publishers correctly in this case, we need to extend the main <code>Publisher</code> protocol:</p>
<pre><code>extension Publisher where Output == Int {
func evenSquared() -> AnyPublisher<Output, Failure> {
return filter {
$0 % 2 == 0
}.map {
$0 * $0
}.eraseToAnyPublisher()
}
}
let evenSquaredPublisher = publisher.evenSquared()</code></pre>
<p>This is better, but we're still not done. Luckily for us (or not, as you'll see below), every one of these Combine operators return an actual concrete <code>Publisher</code> implementation, so with some help of the compiler we can return the correct result of the operation instead of <code>AnyPublisher</code>:</p>
<pre><code>extension Publisher where Output == Int {
func evenSquared() -> Publishers.Map<Publishers.Filter<Self>, Output> {
return filter {
$0 % 2 == 0
}.map {
$0 * $0
}
}
}</code></pre>
<p>The signature of methods might let a little large because of this, but as far as I know, this is the correct way of approaching this problem, and you can make it better in this case with an alias:</p>
<pre><code>typealias EvenSquaredPublisher<P: Publisher, T> = Publishers.Map<Publishers.Filter<P>, T>
extension Publisher where Output == Int {
func evenSquared() -> EvenSquaredPublisher<Self, Output> {
return filter {
$0 % 2 == 0
}.map {
$0 * $0
}
}
}</code></pre>
<p>So far this seems like nothing special, but don't worry, this is going to get weird pretty soon.</p>
<h2>The Hardcore Case: Extending Publishers With Generic Outputs</h2>
<p>There's one additional case I would like to show you, which is what prompted me to write this article. <b>What if the output itself contains generics?</b></p>
<pre><code>enum Condition<T> {
case satisfied(T)
case unsatisfied
}
let publisher = CurrentValueSubject<Condition<Int>, Never>(.satisfied(1))
let publisherB = CurrentValueSubject<Condition<Int>, Never>(.satisfied(2))
let combinedConditions = publisher.combineLatest(publisherB).map { tuple in
guard case .satisfied(let pA) = tuple.0, case .satisfied(let pB) = tuple.1 else {
return .unsatisfied
}
return .satisfied((pA, pB))
}</code></pre>
<p>In this example, we're merging the contents of two conditions into a single condition that contains both publisher's values. But because the result here is <code>Condition<T></code>, we can't use the constrained extension syntax anymore:</p>
<pre><code>extension Publisher where Output == Condition
// Reference to generic type 'Condition' requires arguments in <...></code></pre>
<p>I personally find it really weird that this is not possible to do, and perhaps a point of improvement with Swift in the future. Still, there's a way you can achieve this. in <i>this</i> case, the correct approach is to instead constrain <b>the method itself</b>:</p>
<pre><code>extension Publisher {
func combineCondition<A, B, P: Publisher>(
_ publisher: P
) -> Publishers.Map<Publishers.CombineLatest<Self, P>, Condition<(A, B)>>
where Output == Condition<A>, P.Output == Condition<B>, Failure == P.Failure {
return combineLatest(publisher).map { tuple in
guard case .satisfied(let pA) = tuple.0, case .satisfied(let pB) = tuple.1 else {
return .unsatisfied
}
return .satisfied((pA, pB))
}
}
}</code></pre>
<p>As promised, things got weird pretty fast. Besides constraining the initial publisher's output to match the desired <code>Condition</code> type through an unconstrained generic <code>A</code> type in the method's signature, we also need to make sure that the merging publisher's <code>Failure</code> type matches the one that triggered the operation. That's a really big method!</p>
<p>To wrap it up, let me show you how to achieve the same thing when a custom type is used instead. In this case, we can do the same thing in the class's initializer:</p>
<pre><code>final class CombinedConditionPublisher<A, B, F: Error>: Publisher {
typealias Output = Condition<(A, B)>
typealias Failure = F
let combined: AnyPublisher<Condition<(A, B)>, F>
init<PA: Publisher, PB: Publisher>(
_ a: PA,
_ b: PB
)
where PA.Failure == F, PB.Failure == F, PA.Output == Condition<A>, PB.Output == Condition<B>
{
combined = a.combineLatest(b).map { tuple in
guard case .satisfied(let pA) = tuple.0, case .satisfied(let pB) = tuple.1 else {
return .unsatisfied
}
return .satisfied((pA, pB))
}.eraseToAnyPublisher()
}
func receive<S>(subscriber: S) where S : Subscriber, Failure == S.Failure, Output == S.Input {
combined.receive(subscriber: subscriber)
}
}
extension Publisher {
func combineCondition<A, B, P: Publisher>(
_ publisher: P
) -> CombinedConditionPublisher<A, B, Failure>
where Output == Condition<A>, P.Output == Condition<B>, Failure == P.Failure {
return CombinedConditionPublisher(self, publisher)
}
}</code></pre>
<p>This case is a little more complex though, because we now need to use <code>AnyPublisher</code> to cover the fact that we cannot constrain <code>PA</code> and <code>PB</code> in the class's main definition. Still, the functionality will be the same.</p>
<div class="sponsor-article-ad-auto hidden"></div>
<p>While it's unfortunate that the signatures are enormous, things will look perfect on the call site. As mentioned before, as weird as it looks, this seems to be exactly how Combine implements some of its operators.</p>
<pre><code>let publisher = CurrentValueSubject<Condition<Int>, Never>(.satisfied(1))
let publisherB = CurrentValueSubject<Condition<Int>, Never>(.satisfied(2))
let combined = publisher.combineCondition(publisherB)</code></pre>
</div>
</div>
<div class="blog-post footer-main">
<div class="footer-logos">
<a href="https://swiftrocks.com/rss.xml"><i class="fa fa-rss"></i></a>
<a href="https://twitter.com/rockbruno_"><i class="fa fa-twitter"></i></a>
<a href="https://github.com/rockbruno"><i class="fa fa-github"></i></a>
</div>
<div class="footer-text">
© 2025 Bruno Rocha
</div>
<div class="footer-text">
<p><a href="https://swiftrocks.com">Home</a> / <a href="blog">See all posts</a></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Blog Post (Right Sidebar) End -->
</div>
</div>
</div>
<!-- All Javascript Plugins -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script type="text/javascript" src="js/prism4.js"></script>
<!-- Main Javascript File -->
<script type="text/javascript" src="js/scripts30.js"></script>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-H8KZTWSQ1R"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-H8KZTWSQ1R');
</script>
</body>
</html>