<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by czater on Medium]]></title>
        <description><![CDATA[Stories by czater on Medium]]></description>
        <link>https://medium.com/@czater?source=rss-c093e1c7ca97------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*7nBDk4PJNlByjdEohLNPFA.png</url>
            <title>Stories by czater on Medium</title>
            <link>https://medium.com/@czater?source=rss-c093e1c7ca97------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 08:34:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@czater/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Swift & Redux: Asynchronous]]></title>
            <link>https://medium.com/@czater/swift-redux-asynchronous-6037bc43dd10?source=rss-c093e1c7ca97------2</link>
            <guid isPermaLink="false">https://medium.com/p/6037bc43dd10</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[czater]]></dc:creator>
            <pubDate>Mon, 04 May 2020 13:06:49 GMT</pubDate>
            <atom:updated>2020-05-04T13:06:49.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQpKOI3QkmFYbVvMY0O24A.png" /></figure><p>All actions dispatched by the reducer are synchronous — every new state is generated synchronously. So how asynchronous things — like API calls — are handled by <em>Redux</em>? There are at least a dozen ways to handle this issue and today I want to show you the way that utilises <em>Combine</em> framework. Let’s start with downloading some data from the API.</p><p>In this example, the state consists of two fields — users and posts.</p><pre>struct State {<br>  var users: [String]<br>  var posts: [String]<br>  <br>  static func `default`() -&gt; State {<br>    return .init(users: [], posts: [])<br>  }<br>}</pre><p>There are also two simple actions.</p><pre>enum Action {<br>  case setUsers([String])<br>  case setPosts([String])<br>}</pre><p>And a simple reducer.</p><pre>func reducer(state: inout State, action: Action) -&gt; State { <br>  switch action { <br>    case .setUsers(let users): <br>      state.users = users <br>    case .setPosts(let posts): <br>      state.posts = posts <br>  }</pre><pre>  return state <br>}</pre><p>And a simple store.</p><pre>class Store { <br>  private(set) var state: State <br>  <br>  init(state: State = .default()) { <br>    self.state = state <br>  } <br>   <br>  public func dispatch(action: Action) {<br>    state = reducer(state: &amp;state, action: action) <br>  }<br>}</pre><p>Now let’s define our models — <em>Users</em> and <em>Posts</em>.</p><pre>struct Posts: Codable {<br>  let data: [String] <br>} </pre><pre>struct Users: Codable {<br>  let data: [String] <br>}</pre><p>Now we can start handling the asynchronous code, let’s start with defining <em>AsyncAction</em> — <em>getUsers</em> and <em>getPosts</em>.</p><pre>enum AsyncAction { <br>  case getUsers <br>  case getPosts <br>}</pre><p>The basic idea behind this approach looks like this:</p><ol><li>Get the asynchronous action.</li><li>Map it and delegate solving it to the right place — i.e. to the network service.</li><li>Wait for a result.</li><li>Map the result to the <em>Action</em> — the regular one — and reduce it.</li></ol><p>This can be easily achieved thanks to the <em>Combine</em> framework.</p><p>At first, we can create a network service with two methods — <em>getUsers</em> and <em>getPosts</em>.</p><pre>class NetworkService { <br>  private let usersURL = URL(string: &quot;http://www.mocky.io/v2/5e58f1832f000020979622b7&quot;)! <br>  private let postsURL = URL(string: &quot;http://www.mocky.io/v2/5e59dd6830000054001f0a56&quot;)! </pre><pre>  func getUsers() -&gt; AnyPublisher&lt;Action, Never&gt; { <br>    return URLSession.shared<br>      .dataTaskPublisher(for: usersURL)<br>      .map { $0.data }<br>      .decode(type: Users.self, decoder: JSONDecoder())  <br>      .replaceError(with: .init(data: [&quot;&quot;]))<br>      .map { users -&gt; Action in .setUsers(users.data) }<br>      .eraseToAnyPublisher() <br>  } </pre><pre>  func getPosts() -&gt; AnyPublisher&lt;Action, Never&gt; { <br>    return URLSession.shared.dataTaskPublisher(for: postsURL)<br>      .map { $0.data }<br>      .decode(type: Posts.self, decoder: JSONDecoder())<br>      .replaceError(with: .init(data: [&quot;&quot;]))<br>      .map { posts -&gt; Action in .setPosts(posts.data) } <br>      .eraseToAnyPublisher() <br>  } <br>}</pre><p>These methods work pretty much straight forward:</p><ol><li>Creating a dataTaskPublisher with a given URL.</li><li>Getting the data from the response.</li><li>Decode the data to the appropriate type.</li><li>Replace a potential error with empty data.</li><li>Map the data to the right action and return it as a publisher.</li></ol><p>The newest Apple’s framework shines in this type of tasks.</p><p>The next things that we have to implement to support asynchronous functions execution are a new dispatch function that accepts an <em>AsyncAction</em> as a parameter and two new variables — <em>networkService</em> and <em>cancellables</em>.</p><pre>class Store { <br>  private(set) var state: State <br>  private let networkService: NetworkService <br>  private var cancellables: Set&lt;AnyCancellable&gt; = [] </pre><pre>  init(state: State = .default(), networkService: NetworkService = .init()) { <br>    self.state = state<br>    self.networkService = networkService<br>  } <br>  <br>  public func dispatch(action: Action) { <br>    state = reducer(state: &amp;state, action: action) <br>  }</pre><pre>  public func dispatch(action: AsyncAction) { </pre><pre>    func mapToAction(_ action: AsyncAction) -&gt; AnyPublisher&lt;Action, Never&gt; { <br>      switch action { <br>        case .getUsers: <br>          return networkService.getUsers() <br>        case .getPosts: <br>          return networkService.getPosts() <br>      } <br>    } </pre><pre>    mapToAction(action)<br>      .receive(on: DispatchQueue.main)         <br>      .sink(receiveValue: dispatch)         <br>      .store(in: &amp;cancellables)<br>  }<br>}</pre><p>Based on the passed parameter, an appropriate function from the network service is called and a new publisher is being generated. When the publisher completes its task, the “old” dispatch function is called with a proper <em>Action</em> parameter. The current publisher is also removed from the <em>cancellables</em> set. That’s it.</p><p>Let’s try it in action.</p><pre>let store = Store() <br>store.dispatch(action: .getPosts) <br>store.dispatch(action: .getUsers) <br>print(store.state) <br>//State(users: [], posts: []) </pre><pre>DispatchQueue.main.asyncAfter(deadline: .now() + 2) { <br>  print(store.state)<br>}<br>//After 2 seconds…<br>//State(users: [&quot;Sam&quot;, &quot;Bob&quot;, &quot;Alice&quot;], posts: [&quot;Hi&quot;, &quot;Hello&quot;, &quot;How are you?&quot;, &quot;Good!!&quot;])</pre><p>Everything works as expected.</p><p>As I mentioned at the beginning there are probably a dozen ways to handle asynchronous code execution in <em>Redux</em>. Another good approach would be to use <em>Middleware</em> and I will write about it in the next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6037bc43dd10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift & Redux]]></title>
            <link>https://medium.com/macoclock/swift-redux-feceef498188?source=rss-c093e1c7ca97------2</link>
            <guid isPermaLink="false">https://medium.com/p/feceef498188</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[czater]]></dc:creator>
            <pubDate>Thu, 30 Apr 2020 12:07:15 GMT</pubDate>
            <atom:updated>2020-05-04T22:44:09.945Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WJD5kFI8_MNp2XQY8N_Vcw.png" /></figure><h3>Swift &amp; Redux: Basics</h3><p>Redux is an app architecture based on the idea of a single source of truth — it can be either a single struct or composition of structs — that is accessible from any place within the app. It was created in 2015 by Dan Abramov and Andrew Clark and has since then been widely used in the frontend world. The popularity of Redux in the mobile world highly increased with the appearance of the first-party reactive UI frameworks such as Flutter and SwiftUI because they work together very well.</p><p>Redux is built from several elements: state, action, reducer, and store.</p><p>The state is a container for all the information needed by our app. It can be read directly but cannot be modified directly. To change it we have to use actions. An <em>action</em> represents a state mutation — it could be a simple enum, struct or class, that holds new information that will be added to the state. <em>Reducer</em> is a pure function that takes two parameters — an action and current state — and returns a new state. A store is an object that holds state and exposes methods to read &amp; modify it. Let’s now take a look at the minimal implementation example.</p><pre>struct AppState {<br>  var counter: Int<br>}</pre><p>An <em>AppState</em> contains only a counter variable that can be modified using the below <em>actions</em>.</p><pre>enum AppAction {<br>  case add(value: Int)<br>  case subtract(value: Int)<br>}</pre><p>An <em>AppAction</em> enum contains only two actions with associated value — add and subtract.</p><pre>func appReducer(state: inout AppState, action: AppAction) -&gt; AppState {<br>  switch action {<br>    case .add(let value):<br>      state.counter += value<br>    case .subtract(let value):<br>      state.counter -= value<br>  }</pre><pre>  return state<br>}</pre><p>An <em>appReducer</em> function utilises the app’s state and actions to add or subtract value to the state’s counter.</p><pre>class AppStore {<br>  private(set) var state: AppState<br>  <br>  init(state: AppState = .init(counter: 0)) {<br>    self.state = state<br>  }</pre><pre>  public func dispatch(action: AppAction) {<br>    state = appReducer(state: &amp;state, action: action)<br>  }<br>}</pre><p>An <em>AppStore</em> contains a state variable that is readable but not modifiable directly — exactly as it should be. A <em>dispatch</em> function makes the state modification possible.</p><p>Let’s try to use all these pieces together.</p><pre>let store = AppStore()<br>print(store.state.counter) //0<br>store.dispatch(action: .add(value: 5))<br>print(store.state.counter) //5<br>store.dispatch(action: .subtract(value: 3))<br>print(store.state.counter) //2</pre><p>It works like a charm.</p><p>In conclusion, Redux is a well-defined app architecture with multiple advantages, such as prediction — for the same set of actions, the same new state is going to be generated, centralisation — an app’s state with all the needed tools in one place, and testability — tests are extremely easy to write and perform.</p><p>Of course, it is not free from flaws as well. Memory usage might be high when the state is very complex which could lead to poor app performance. Also, it might be hard to implement Redux in the iOS world in some specific scenarios — i.e. in the camera app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=feceef498188" width="1" height="1" alt=""><hr><p><a href="https://medium.com/macoclock/swift-redux-feceef498188">Swift &amp; Redux</a> was originally published in <a href="https://medium.com/macoclock">Mac O’Clock</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>