{"id":387878,"date":"2024-06-29T07:35:33","date_gmt":"2024-06-29T07:35:33","guid":{"rendered":"http:\/\/savepearlharbor.com\/?p=387878"},"modified":"-0001-11-30T00:00:00","modified_gmt":"-0001-11-29T21:00:00","slug":"","status":"publish","type":"post","link":"https:\/\/savepearlharbor.com\/?p=387878","title":{"rendered":"<span>How to cook reactive programming. Part 2: Side effects<\/span>"},"content":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-1\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<p>Despite the number, this is the third article about reactive programming. Today we are going to talk about how to handle side effects while using unidirectional approaches.<\/p>\n<p><a name=\"habracut\"><\/a>  <\/p>\n<blockquote><p>Before we start, I\u2019d firstly highly recommend reading at least <a href=\"https:\/\/medium.com\/@atimca\/how-to-cook-reactive-programming-part-1-unidirectional-architectures-introduction-5c73f3f7793d?source=friends_link&amp;sk=56793e72690bb9703560cfc686d29aa7\" rel=\"nofollow\">How to cook reactive programming. Part 1: Unidirectional architectures introduction.<\/a>. However, if you\u2019re not familiar with frameworks such as <code>RxSwift<\/code> or <code>Combine<\/code>, or reactive programming in general, I\u2019d suggest reading <a href=\"https:\/\/medium.com\/atimca\/what-is-reactive-programming-43e60cc4c0f?source=friends_link&amp;sk=4ab8aa82f6e669bad59be42cba67e0ef\" rel=\"nofollow\">this article<\/a> as well.<\/p><\/blockquote>\n<p>  <\/p>\n<ol>\n<li><a href=\"https:\/\/medium.com\/atimca\/what-is-reactive-programming-43e60cc4c0f?source=friends_link&amp;sk=4ab8aa82f6e669bad59be42cba67e0ef\" rel=\"nofollow\">What is Reactive Programming? iOS Edition<\/a><\/li>\n<li><a href=\"https:\/\/medium.com\/@atimca\/how-to-cook-reactive-programming-part-1-unidirectional-architectures-introduction-5c73f3f7793d?source=friends_link&amp;sk=56793e72690bb9703560cfc686d29aa7\" rel=\"nofollow\">How to cook reactive programming. Part 1: Unidirectional architectures introduction.<\/a><\/li>\n<\/ol>\n<p>  <\/p>\n<h2 id=\"intro\">Intro<\/h2>\n<p>  <\/p>\n<p>Before we will move to the talk about <code>Side Effects<\/code> I want to introduce you to the main subject of this article.<\/p>\n<p>  <\/p>\n<div style=\"text-align:center;\"><img decoding=\"async\" src=\"https:\/\/habrastorage.org\/r\/w1560\/webt\/qk\/jr\/9o\/qkjr9oemnaghvt4qvdsuzrwv2jy.png\" data-src=\"https:\/\/habrastorage.org\/webt\/qk\/jr\/9o\/qkjr9oemnaghvt4qvdsuzrwv2jy.png\"\/><\/div>\n<p>  <\/p>\n<p>This is a representation of the simplest <code>State<\/code> which you actually can find in nearly every application. Let me transform this image into the real code.<\/p>\n<p>  <\/p>\n<pre><code class=\"swift\">enum State {     case initial     case loading     case loaded(data: [String]) }<\/code><\/pre>\n<p>  <\/p>\n<p>Much better! If you\u2019re familiar with a state machine theory from the computer science class, this picture will be very recognisable to you. This is a simple state machine with 3 states. The <code>Initial<\/code> state can go to the <code>Loading<\/code> state. The <code>Loading<\/code> state to the <code>Loaded<\/code> state. And the <code>Loaded<\/code> state can go back to the <code>Loading<\/code> state. Remember I was talking about <code>State<\/code> data consistency. In this particular case it&#8217;s really hard to make the state inconsistent. Each state of the system is represented as an enum case.<\/p>\n<p>  <\/p>\n<p>Don&#8217;t worry, I&#8217;m not going to bother you with any computer science concepts here. It was mostly a representation of the ideal <code>State<\/code> which could be achieved. In the real world it&#8217;s really hard to create only an enum state. In most cases it would be a structure. However, for the purposes of this article we will use this <code>State<\/code> for the experiments. And now let&#8217;s move to the main topic.<\/p>\n<p>  <\/p>\n<h2 id=\"what-are-side-effects\">What are Side Effects?<\/h2>\n<p>  <\/p>\n<p>According to <strong>Wikipedia<\/strong><\/p>\n<p>  <\/p>\n<blockquote><p>In computer science, an operation, function or expression is said to have a side effect if it modifies some state variable value(s) outside its local environment, that is to say has an observable effect besides returning a value (the main effect) to the invoker of the operation. State data updated &#171;outside&#187; of the operation may be maintained &#171;inside&#187; a stateful object or a wider stateful system within which the operation is performed. Example side effects include modifying a non-local variable, modifying a static local variable, modifying a mutable argument passed by reference, performing I\/O or calling other side-effect functions. In the presence of side effects, a program&#8217;s behaviour may depend on history; that is, the order of evaluation matters. Understanding and debugging a function with side effects requires knowledge about the context and its possible histories.<\/p><\/blockquote>\n<p>However, here we\u2019re not talking about the strict definition of the side effects. Let&#8217;s remember where we ended up the last time.<\/p>\n<p>  <\/p>\n<pre><code class=\"swift\">struct State {     var value: Int?      static func reduce(state: State, event: Event) -> State {         var state = state         switch event {         case .changeValue(let newValue):             state.value = newValue         }         return state     } }  class Store {     var state: State      func accept(event: Event) {         state = reduce(state: state, event: event)     } }<\/code><\/pre>\n<p>  <\/p>\n<p>Generally, nearly all unidirectional architectures look like this. We have a <code>State<\/code> on which the rest application relies as only one source of truth. A <code>reducer<\/code> which alongside <code>Event<\/code> is the only way to mutate or update <code>State<\/code>. However, there should be something else. We don&#8217;t live in a synchronous world, where every update for <code>State<\/code> can be done only with a synchronous <code>reduce<\/code> function. Every application needs to go to the network or database, for the new cat images. Every developer moves even hard computations on the background thread. So, how will all of this work with the existing code? The answer is side effects. In our case <code>Side Effects<\/code> are something asynchronous, which could mutate <code>State<\/code> and this &#171;something&#187; works on the side of the <code>reducer<\/code>. Imagine your beloved network service which somehow needs to be connected to the rest of the system. But first let&#8217;s talk about why this architecture is called \u2018unidirectional\u2019.<\/p>\n<p>  <\/p>\n<p>One remark: <code>Event<\/code> in different implementations of unidirectional architectures could be called a <code>Mutation<\/code> or <code>Action<\/code> or <code>Message<\/code>, or maybe something different, for our purposes however naming is not so important. <\/p>\n<p>  <\/p>\n<h2 id=\"why-is-the-architecture-called-unidirectional\">Why is the architecture called unidirectional?<\/h2>\n<p>  <\/p>\n<p>Unidirectional architecture is also known as one-way data flow. This means that data has one, and only one way to be transferred to other parts of the application. In essence, this means child components are not able to update the data that is coming from the parent component. The main benefit of this approach is that data flows throughout your app in a single direction, giving you better control over it.<\/p>\n<p>  <\/p>\n<p>I think it should be quite easy to understand with the<code>State<\/code> <code>reduce<\/code> approach from the beginning. We can change or mutate <code>State<\/code> only with a strict described <code>Event<\/code>. As a result we&#8217;ve got a one-way (unidirectional) data flow. However, what should we do with <code>Side Effects<\/code>? <\/p>\n<p>  <\/p>\n<p>Imagine that for the <code>State<\/code> we have a service which as a result returns a list of the news titles.<\/p>\n<p>  <\/p>\n<pre><code class=\"swift\">func loadNewsTitles(completionHandler: ([String]) -> ()) {     completionHandler([\"title1\", \"title2\"]) }<\/code><\/pre>\n<p>  <\/p>\n<p>We know that <code>reducer<\/code> takes <code>Event<\/code> as an input not a closure\u2026 How can we connect this service to the <code>reducer<\/code>? The answer is quite simple. Let\u2019s have a <code>Side Effect<\/code>, which will return <code>Event<\/code>, not just requested data.<\/p>\n<p>  <\/p>\n<p>The resulting system will look like this:<\/p>\n<p>  <\/p>\n<pre><code class=\"swift\">enum State {     case initial     case loading     case loaded(data: [String]) }  enum Event {     case dataLoaded(data: [String])     case loadData }  func loadNewsTitles(completionHandler: (Event) -> ()) {     loadNewsTitles { data in         completionHandler(.dataLoaded(data: data))     } }  extension State {     static func reduce(state: State, event: Event) -> State {         var state = state         switch event {         case .dataLoaded(let data):             state = .loaded(data: data)         case .loadData:             state = .loading         }         return state     } }<\/code><\/pre>\n<p>  <\/p>\n<p>As you can see for now <code>loadNewsTitles<\/code> returns an <code>Event<\/code>, which could mutate the state. Our system works only in a unidirectional way. And there&#8217;s an answer to why the architecture is called <code>Unidirectional<\/code>. After I\u2019d answered one question, I&#8217;ve subsequently produced another one. How can we connect <code>Side Effects<\/code> and the rest of the system? This question actually is the most complicated so far. I&#8217;ll try to answer it in the next section.<\/p>\n<p>  <\/p>\n<h2 id=\"which-types-of-side-effects-exist\">Which types of side effects exist?<\/h2>\n<p>  <\/p>\n<p>In nearly every <code>unidirectional architecture<\/code> you&#8217;ll see a collaboration of <code>State<\/code> and some function for <code>reducing<\/code> this <code>State<\/code> according to the input <code>Event<\/code>. With <code>Side Effects<\/code> it&#8217;s much more complicated. Almost every framework does this in a different way. Let me try to make you familiar with the most popular of them.<\/p>\n<p>  <\/p>\n<h3 id=\"middleware\">Middleware<\/h3>\n<p>  <\/p>\n<p>Let&#8217;s start with the <code>Middleware<\/code> approach. <code>Middleware<\/code> provides a third-party extension point between dispatching an <code>Event<\/code>, and the moment it reaches the reducer. In simple terms <code>Middleware<\/code>, sits in the middle between you performing or dispatching an <code>Event<\/code> and mutating your <code>State<\/code> inside the <code>reducer<\/code>.<\/p>\n<p>  <\/p>\n<div style=\"text-align:center;\"><img decoding=\"async\" src=\"https:\/\/habrastorage.org\/r\/w1560\/webt\/xd\/2r\/g5\/xd2rg5cqxho59k9ibk6n9k53j_i.png\" data-src=\"https:\/\/habrastorage.org\/webt\/xd\/2r\/g5\/xd2rg5cqxho59k9ibk6n9k53j_i.png\"\/><\/div>\n<p>  <\/p>\n<p>Let me provide you with a code example, which I found in one well-known framework for <code>Redux<\/code> implementation for Swift.<\/p>\n<p>  <\/p>\n<pre><code class=\"swift\">let middleware: Middleware = { store, getState in     return { next in         return { event in             \/\/ perform middleware logic             switch event {             case .loadData:                 loadNewsTitles { event in                     store.accept(event)                 }             case .dataLoaded:                 break             }              \/\/ call next middleware             return next(event)         }     } }<\/code><\/pre>\n<p>  <\/p>\n<p>As you can see a <code>Middleware<\/code> could be treated as an asynchronous pre<code>Reducer<\/code>. It catches all <code>Events<\/code>, carries out some manipulations over it \u2014 in our case, loading news titles -, and performs a new <code>Event<\/code> for the system if it&#8217;s necessary. So, if the <code>Event<\/code> is <code>loadData<\/code>, listed <code>Middleware<\/code> will load news titles and in the closure send another <code>Event<\/code> to the <code>Store<\/code>. The next <code>dataLoaded<\/code> <code>Event<\/code> will just be ignored by this <code>Middleware<\/code>. One of the pros of this method is the possibility to chain <code>Middlewares<\/code> quite easily.<\/p>\n<p>  <\/p>\n<p>Also, if you want to read more about this approach, I\u2019d highly recommend taking a look at <a href=\"http:\/\/reswift.github.io\/ReSwift\/master\/getting-started-guide.html\" rel=\"nofollow\"><code>ReSwift<\/code> framework<\/a>. This framework is an implementation of a unidirectional architecture, which is called <code>Redux<\/code> for Swift language. For those, who still refuse reactive frameworks, <code>ReSwift<\/code> could be a good start, because <code>ReSwift<\/code> doesn&#8217;t use any.<\/p>\n<p>  <\/p>\n<h3 id=\"effects\">Effects<\/h3>\n<p>  <\/p>\n<p>The next approach I want to talk about is the <code>Effects<\/code> approach. The main idea is almost the same as the <code>Middleware<\/code>, but all actions are going on inside <code>Reducer<\/code> itself.<\/p>\n<p>  <\/p>\n<div style=\"text-align:center;\"><img decoding=\"async\" src=\"https:\/\/habrastorage.org\/r\/w1560\/webt\/se\/kn\/xc\/seknxcc53cyslptjsfiozkn2ab4.png\" data-src=\"https:\/\/habrastorage.org\/webt\/se\/kn\/xc\/seknxcc53cyslptjsfiozkn2ab4.png\"\/><\/div>\n<p>  <\/p>\n<p>In this approach <code>Reducer<\/code> has a little bit of a different shape, that I showed you before. It has a shape, which you can see below.<\/p>\n<p>  <\/p>\n<pre><code class=\"swift\">func reducer(state: inout State, event: Event, environment: Environment) -> Effect<\/code><\/pre>\n<p>  <\/p>\n<p>Nearly everything should be familiar. <code>State<\/code> is a type that holds the current state of the application. <code>Event<\/code> is a type that holds all possible events that cause the state of the application to change. However, there are two new characters: <code>Environment<\/code> and <code>Effect<\/code>. <code>Environment<\/code> is a type that holds all dependencies needed in order to produce <code>Effect(s)<\/code>, such as API clients, analytics clients, random number generators, and so on.<\/p>\n<p>  <\/p>\n<p>So, how does it work for our example?<\/p>\n<p>  <\/p>\n<pre><code class=\"swift\">struct Environment {     let loadNewsTitles: (Event) -> () }  struct Effect {     init(work: ((State) -> ())? = nil)     func performWorkItem() -> Event }  extension Effect {     \/\/\/ An effect that does nothing and completes immediately.     static let none = Effect() }  extension Effect {     static func loadNewTitlesEffect(loadNewsTitles: (Event) -> ()) -> Effect }  func reducer(state: inout State, event: Event, environment: Environment) -> Effect {     switch event {     case .dataLoaded(data: let data):         state = .loaded(data: data)         return .none     case .loadData:         return Effect.loadNewTitlesEffect(loadNewsTitles: environment.loadNewsTitles)     } }<\/code><\/pre>\n<p>  <\/p>\n<p>How does this approach work? For every call of <code>Reducer<\/code> you provide all necessary dependencies via <code>Environment<\/code> to the <code>Reducer<\/code> itself, and afterward your <code>Store<\/code> will perform every <code>workItem<\/code> from the <code>Effect<\/code> itself. And then every <code>Effect<\/code> will return another <code>Event<\/code> to the <code>Reducer<\/code>. Unidirectional data flow works with all power here.<\/p>\n<p>  <\/p>\n<p>You may ask, but what about the pure <code>Reducer<\/code> over there? You told us that <code>Reducer<\/code> is a pure function, and now you put <code>Side Effects<\/code> directly inside this function. Moreover, we mutate <code>State<\/code> inside this function, not just creating a new value. So, I can definitely explain that this variation of the <code>Reducer<\/code> is the most complicated one which we&#8217;ve seen so far. It has the <code>Environment<\/code> inside and it mutates <code>State<\/code>. However, let\u2019s take a closer look. If we provide one implementation for the <code>loadNewTitles<\/code> service, our <code>Reducer<\/code> will perform the same and our <code>State<\/code> in the end will be the same. Yeah, in the real world, our server can answer with the different replies or different news titles, but it still has the same output \u2014 <code>Effect<\/code> as a return value, with the same network client in it. I hope you\u2019ve got the idea. What about <code>State<\/code> mutation? Since all real mutations are always going on inside the <code>Store<\/code>, the main situation around changing <code>State<\/code> hasn&#8217;t changed itself. Moreover, mutating <code>State<\/code> against creating new values for every <code>reduce<\/code> saves some performance for us. We don&#8217;t need to allocate new memory each time.<\/p>\n<p>  <\/p>\n<p>I don&#8217;t want to provide a working example of this approach as well. My job is to make you familiar with it and explain the basics. However, I highly recommend taking a look at <a href=\"https:\/\/github.com\/pointfreeco\/swift-composable-architecture.git\" rel=\"nofollow\"><code>The Composable Architecture TCA<\/code><\/a> from pointfree.co. In my personal opinion this framework is the most promising for now. It has its own cons such as the minimum iOS 13 version. They also have a website with a lot of useful videos available on it. It&#8217;s not free, but I have a <a href=\"https:\/\/www.pointfree.co\/subscribe\/personal?ref=hnNgUrZA\" rel=\"nofollow\">promocode for you<\/a>. I&#8217;m sorry I couldn&#8217;t miss this chance&#8230;<\/p>\n<p>  <\/p>\n<h3 id=\"query-feedback\">Query Feedback<\/h3>\n<p>  <\/p>\n<p>Let&#8217;s move forward or downstairs. In contrast with <code>Middleware<\/code> or <code>Effect<\/code> approaches from the previous sections, there&#8217;s a <code>Query<\/code> approach. The <code>Query Feedback<\/code> approach <code>reacts<\/code> to new changes from the different side of the <code>Reducer<\/code> compared to <code>Middleware<\/code>.<\/p>\n<p>  <\/p>\n<div style=\"text-align:center;\"><img decoding=\"async\" src=\"https:\/\/habrastorage.org\/r\/w1560\/webt\/sb\/ke\/nj\/sbkenj9axk8_xayeqwsfwigpjlm.png\" data-src=\"https:\/\/habrastorage.org\/webt\/sb\/ke\/nj\/sbkenj9axk8_xayeqwsfwigpjlm.png\"\/><\/div>\n<p>  <\/p>\n<p>Did you notice? We\u2019ve moved the whole way through <code>Side Effects<\/code> approaches? <code>Middleware<\/code> was before <code>Reducer<\/code>, <code>Effects<\/code> approach was inside <code>Reducer<\/code> and now <code>Query Feedback<\/code> is after reducer. Quite a journey, huh?<\/p>\n<p>  <\/p>\n<p>However, how does it work? We need to take a small piece of the <code>State<\/code> and start to <code>Observe<\/code> every change of this state. For the previous example it will look like:<\/p>\n<p>  <\/p>\n<pre><code class=\"swift\">extension State {     var loadQuery: Void? {         guard case .loading = self else { return nil }         return ()     } }<\/code><\/pre>\n<p>  <\/p>\n<p>In other words, there&#8217;s some kind of <code>Observer<\/code>, which follows every change of this query and performs some actions over it. The optional <code>Void<\/code> type for my taste is the best representation when you need to understand whether you need to do any work or not.<\/p>\n<p>  <\/p>\n<p>I think you\u2019ve likely become bored with non-working examples in this article. So, let&#8217;s try at least to implement this one. I&#8217;ll use the <code>Combine<\/code> framework for this implementation. Whoah, this is the third article about reactive programming, and only now I&#8217;ll start to use a reactive framework. Also, afterward, I&#8217;ll explain why I prefer to use <code>Combine<\/code> over vanilla Swift. Technically <code>Combine<\/code> is already vanilla as well, but you\u2019ve got the point.<\/p>\n<p>  <\/p>\n<p>Here is a small table of concepts for those who are new in <code>Combine<\/code>.<\/p>\n<p>  <\/p>\n<ul>\n<li><a href=\"https:\/\/developer.apple.com\/documentation\/combine\/publisher\" rel=\"nofollow\">Publisher declares that a type can transmit a sequence of values over time.<\/a><\/li>\n<li><a href=\"https:\/\/developer.apple.com\/documentation\/combine\/published\" rel=\"nofollow\">@Published is a type that publishes a property marked with an attribute<\/a><\/li>\n<li><a href=\"https:\/\/developer.apple.com\/documentation\/combine\/future\/3362552-sink\" rel=\"nofollow\">Sink attaches a subscriber with closure-based behavior to a publisher<\/a><\/li>\n<li><a href=\"https:\/\/developer.apple.com\/documentation\/combine\/cancellable\" rel=\"nofollow\">Cancellable a protocol indicating that an activity or action supports cancellation.<\/a><\/li>\n<li><a href=\"https:\/\/developer.apple.com\/documentation\/combine\/cancellable\/3343581-store\" rel=\"nofollow\">Store stores this cancellable instance in the specified collection<\/a><\/li>\n<\/ul>\n<p>  <\/p>\n<p>From now a little bit of tutorial started. Everything that I&#8217;ll write below you can copy to your project and play with it afterward.<\/p>\n<p>  <\/p>\n<p>Let&#8217;s introduce our old characters: <code>State<\/code>, <code>Reducer<\/code>, <code>Query<\/code> and <code>Event<\/code>:<\/p>\n<p>  <\/p>\n<pre><code class=\"swift\">enum State: Equatable {     case initial     case loading     case loaded(data: [String]) }  enum Event {     case dataLoaded(data: [String])     case loadData }  extension State {     var loadQuery: Bool {         guard case .loading = self else { return false }         return true     } }  extension State {     static func reduce(state: State, event: Event) -> State {         var state = state         switch event {         case .dataLoaded(let data):             state = .loaded(data: data)         case .loadData:             state = .loading         }         return state     } }<\/code><\/pre>\n<p>  <\/p>\n<p>Nothing new so far \u2014 only a <code>Query<\/code> which I&#8217;ve shown to you recently. Now let&#8217;s remove the callback from <code>loadNewsTitles<\/code> service and rewrite it in <code>Combine<\/code> fashion.<\/p>\n<p>  <\/p>\n<pre><code class=\"swift\">func loadNewsTitles() -> AnyPublisher&lt;[String], Never> {     [\"title1\", \"title2\"]         .publisher         .delay(for: .microseconds(500), scheduler: DispatchQueue.main)         .collect()         .eraseToAnyPublisher() }<\/code><\/pre>\n<p>  <\/p>\n<p>Mostly it&#8217;s just a pre-prepared mock with a small delay, which should simulate a real network environment. And now there&#8217;s a new character in this play. Let&#8217;s call it <code>SideEffects<\/code>. Obviously it\u2019s not me who invented this name, but let&#8217;s imagine it for the bigger narrative of the story.<\/p>\n<p>  <\/p>\n<pre><code class=\"swift\">struct SideEffects {     let loadNewTitles: () -> AnyPublisher&lt;[String], Never>      func downloadNewTitles() -> AnyPublisher&lt;Event, Never> {         loadNewTitles()             .map(Event.dataLoaded)             .eraseToAnyPublisher()     } }<\/code><\/pre>\n<p>  <\/p>\n<p>As far as you can see, <code>SideEffects<\/code> for the <code>Query Feedback<\/code> approach is almost the same thing, as <code>Environment<\/code> for the <code>Effect<\/code> approach. I prefer to keep it as simple as possible, and most of the time it just converts the output from the services into <code>Event<\/code> which could be consumed by the <code>Reducer<\/code>.<\/p>\n<p>  <\/p>\n<p>And for now, there\u2019s only one question left- how do we connect <code>SideEffects<\/code> with the rest of the system? The answer isn\u2019t so complicated, and <code>Combine<\/code> helps with it very much. Let&#8217;s build our boss <code>Store<\/code> entity in which we&#8217;ll connect every piece of our system.<\/p>\n<p>  <\/p>\n<pre><code class=\"swift\">typealias Reducer = (State, Event) -> State  class Store {     @Published private(set) var state: State     private let reducer: Reducer     private let sideEffects: SideEffects      init(         initialState: State,         reducer: @escaping Reducer,         sideEffects: SideEffects     ) {         self.state = initialState         self.reducer = reducer         self.sideEffects = sideEffects     }      func accept(event: Event) {         state = reducer(state, event)     }      func start() -> AnyCancellable {         $state             .map(\\.loadQuery)             .removeDuplicates()             .filter { $0 == true }             .map { _ in () }             .flatMap(sideEffects.downloadNewTitles)             .sink(receiveValue: accept(event:))     } }<\/code><\/pre>\n<p>  <\/p>\n<p>The most interesting part of the code listing above is the <code>start<\/code> function. As far as you can see, I made our <code>SideEffects<\/code> react to the change of the piece of the <code>State<\/code> <code>loadQuery<\/code>. And for every time when our system will be in the <code>loading<\/code> <code>State<\/code>, our <code>SideEffects<\/code> will go to the network service, download new <code>newsTitles<\/code> and notify our system that new titles have been downloaded. Do you see it? Everything in the cycle, all data flow works in the one direction.<\/p>\n<p>  <\/p>\n<p>Let&#8217;s test what I&#8217;ve done so far.<\/p>\n<p>  <\/p>\n<pre><code class=\"swift\">let store = Store(     initialState: .initial,     reducer: State.reduce(state:event:),     sideEffects: SideEffects(         loadNewTitles: loadNewsTitles     ) ) var cancellables: [AnyCancellable] = []  store     .start()     .store(in: &amp;cancellables)  store     .$state     .removeDuplicates()     .sink { state in print(state) }     .store(in: &amp;cancellables)  store.accept(event: .loadData)  \/\/ Console output  \/\/ initial \/\/ loading \/\/ loaded(data: [\"title1\", \"title2\"])<\/code><\/pre>\n<p>  <\/p>\n<p>And it works, as expected! The system started from <code>initial<\/code> <code>state<\/code> then it went to the <code>loading<\/code> <code>state<\/code> after the new <code>Event<\/code> was sent, and ended up in <code>loaded<\/code> <code>state<\/code>. If you want to play with it some more, I&#8217;ve prepared <a href=\"https:\/\/gist.github.com\/c0c48c02088f9ce6543ab6328732b6b4\" rel=\"nofollow\">a gist<\/a>.<\/p>\n<p>  <\/p>\n<p>I know that two <code>Cancelables<\/code> could look a little bit clumsy here, but I didn&#8217;t want to make this example too complicated. There&#8217;s <a href=\"https:\/\/github.com\/NoTests\/RxFeedback.swift\" rel=\"nofollow\"><code>another framework called RxFeedback<\/code><\/a> where all these problems were solved. I think that you&#8217;ve already got it, that this framework uses <code>RxSwift<\/code> from the title, right? However, there&#8217;s a constructor of <code>Observable<\/code> \u2014 it&#8217;s a <code>Publisher<\/code> from the <code>Combine<\/code> \u2014 which creates the whole <code>unidirectional<\/code> system for you.<\/p>\n<p>  <\/p>\n<pre><code class=\"swift\">typealias Feedback&lt;State, Event> = (Observable&lt;State>) -> Observable&lt;Event>  extension Observable {     public static func system&lt;State, Event>(         initialState: State,         reduce: @escaping (State, Event) -> State,         feedback: Feedback&lt;State, Event>...     ) -> Observable&lt;State> }<\/code><\/pre>\n<p>  <\/p>\n<p>Typealias <code>Feedback<\/code> is a <code>SideEffect<\/code> itself. It takes changes in the <code>State<\/code> as an input and provides a sequence of <code>Events as output<\/code>.<\/p>\n<p>  <\/p>\n<p>In my personal opinion, this approach is the most hardcore one. As an advantage, you can take that your <code>State<\/code> always reflects what&#8217;s going on in the system. The previous two rely on <code>Event<\/code> while doing any <code>Side Effects<\/code>, but this one only relies on the <code>State<\/code> itself. If you want to read a little bit more about the pros and cons of the <code>Effect<\/code> and <code>Query<\/code> approaches, you could read my <a href=\"https:\/\/github.com\/pointfreeco\/episode-code-samples\/issues\/53\" rel=\"nofollow\">discussion with TCA creators<\/a>. <\/p>\n<p>  <\/p>\n<h2 id=\"why-do-we-need-a-reactive-framework-for-this\">Why do we need a reactive framework for this?<\/h2>\n<p>  <\/p>\n<p>There are a lot of people who don&#8217;t want to accept any reactive frameworks and don&#8217;t understand why they are even needed. If you\u2019re still reading this, and you are one of them, crash the like or clap button. This section is mostly for those who\u2019ve been intrigued by the <code>Unidirectional<\/code> approach, but for some reason don&#8217;t want to use <code>reactive<\/code> frameworks. Firstly I want to say, that you&#8217;ve already seen in my articles, that there\u2019s nothing to be scared by in<code>reactive<\/code> frameworks and <code>reactive<\/code> programming in general. Most of you already use some techniques from it. I can say that it&#8217;s much more handy to handle your data like a <code>sequence<\/code> or array than work with enormous closures. Use some functions, like <code>filter<\/code>, <code>map<\/code> or <code>reduce<\/code> etc. It really makes your code more clean and understandable. It&#8217;s really hard to make a lot of mistakes from the start if you don&#8217;t know how to cook it. That&#8217;s why I write these articles for you.<\/p>\n<p>  <\/p>\n<p>Let me show you another advantage in a reactive framework usage. Do you remember that I relied on <a href=\"http:\/\/reswift.github.io\/ReSwift\/master\/getting-started-guide.html\" rel=\"nofollow\"><code>ReSwift<\/code> framework<\/a> while showing a <code>Middleware<\/code> approach? This is a great framework, which was written by brilliant people. However, if you try to understand how it works under the hood, or even try to work with it you will end up with structures like this.<\/p>\n<p>  <\/p>\n<pre><code class=\"swift\">    \/\/\/ Creates a middleware function using SimpleMiddleware to create a ReSwift Middleware function.     func createMiddleware&lt;State: StateType>(_ middleware: @escaping SimpleMiddleware&lt;State>) -> Middleware&lt;State> {          return { dispatch, getState in             return { next in                 return { action in                      let context = MiddlewareContext(dispatch: dispatch, getState: getState, next: next)                     if let newAction = middleware(action, context) {                         next(newAction)                     }                 }             }         }     }<\/code><\/pre>\n<p>  <\/p>\n<p>There are three closures inside each other! Moreover, I&#8217;ve used a helper to make it more simple. Of course, you could separate all of this somehow and avoid all the callback hell. However, if you take a look at my previous <code>Query<\/code> example you will see how everything was simple and straightforward. I wanted to say elegant as well, but for elegance it has to be refactored a little bit. If you want to have a closer look at <code>ReSwift<\/code> in action, I did a small <a href=\"https:\/\/github.com\/Atimca\/Currencies\" rel=\"nofollow\">test project<\/a> some time ago.<\/p>\n<p>  <\/p>\n<h2 id=\"outro\">Outro<\/h2>\n<p>  <\/p>\n<p>There&#8217;s no silver bullet on how to handle <code>Side Effects<\/code>. You can decide for yourself what to use. However, I think that most of you and myself will choose some pre-prepared solution like <code>RxFeedback<\/code> or <code>TCA<\/code> or <code>ReSwift<\/code> or something else.<\/p>\n<p>  <\/p>\n<div style=\"text-align:center;\"><img decoding=\"async\" src=\"https:\/\/habrastorage.org\/webt\/dc\/b1\/st\/dcb1stmo5y4lyla5bbzfa56t3wm.gif\" data-src=\"https:\/\/habrastorage.org\/webt\/dc\/b1\/st\/dcb1stmo5y4lyla5bbzfa56t3wm.gif\"\/><\/div>\n<p>  <\/p>\n<p>Finally, I have a chance to show you this gif. I took it from the <code>ReSwift<\/code> repo. This gif in full form represents the whole power of <code>Unidirectional approaches<\/code>. Technically you can store the whole history of <code>State<\/code> mutations and replay them at any moment you want. <\/p>\n<p>  <\/p>\n<p>So far, you&#8217;ve become familiar with how to work and even how to build your own reactive framework and unidirectional architecture. However, we live in a world where applications are not one button flashlight apps anymore. We have teams of more than ten people. And if you noticed, the main idea of <code>Unidirectional architecture<\/code> is to keep all data inside one struct. I bet, if you start with this approach you will end up with a huge <code>State<\/code> and <code>Reducer<\/code> if not at the end of the week, then by at the end of the month. You may wonder how it&#8217;s possible to separate the <code>Unidirectional<\/code> approach on different modules when the main idea is to keep everything in one place. What to do in this situation and what are the ways of app modularization I will show you in the next article. Let&#8217;s keep in touch!<\/p>\n<p>  <\/p>\n<p>If you don&#8217;t want to lose any new articles <code>subscribe<\/code> to my <a href=\"https:\/\/twitter.com\/atimca\" rel=\"nofollow\">twitter account<\/a>))<\/p>\n<p>  <\/p>\n<pre><code class=\"swift\">Twitter(.atimca) .subscribe(onNext: { newArcticle in     you.read(newArticle) })<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<p><!----><!----><\/div>\n<p><!----><!----><br \/> \u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/507290\/\"> https:\/\/habr.com\/ru\/articles\/507290\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-1\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<p>Despite the number, this is the third article about reactive programming. Today we are going to talk about how to handle side effects while using unidirectional approaches.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"class_list":["post-387878","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/387878","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=387878"}],"version-history":[{"count":0,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/387878\/revisions"}],"wp:attachment":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=387878"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=387878"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=387878"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}