{"id":1846,"url":"https://github.com/BendingSpoons/katana-swift","last_synced_at":"2025-08-06T13:32:22.782Z","repository":{"id":44845753,"uuid":"65275953","full_name":"BendingSpoons/katana-swift","owner":"BendingSpoons","description":"Swift Apps in a Swoosh! A modern framework for creating iOS apps, inspired by Redux.","archived":true,"fork":false,"pushed_at":"2022-11-08T10:17:51.000Z","size":83300,"stargazers_count":2251,"open_issues_count":0,"forks_count":90,"subscribers_count":63,"default_branch":"master","last_synced_at":"2024-10-29T15:17:20.024Z","etag":null,"topics":["ios","katana","redux","swift","ui"],"latest_commit_sha":null,"homepage":"http://bendingspoons.com","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/BendingSpoons.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-08-09T08:09:22.000Z","updated_at":"2024-10-22T11:20:40.000Z","dependencies_parsed_at":"2022-08-26T05:40:39.768Z","dependency_job_id":null,"html_url":"https://github.com/BendingSpoons/katana-swift","commit_stats":null,"previous_names":[],"tags_count":52,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BendingSpoons%2Fkatana-swift","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BendingSpoons%2Fkatana-swift/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BendingSpoons%2Fkatana-swift/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BendingSpoons%2Fkatana-swift/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/BendingSpoons","download_url":"https://codeload.github.com/BendingSpoons/katana-swift/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228905462,"owners_count":17989771,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ios","katana","redux","swift","ui"],"created_at":"2024-01-05T20:15:57.178Z","updated_at":"2024-12-09T14:30:50.428Z","avatar_url":"https://github.com/BendingSpoons.png","language":"Swift","funding_links":[],"categories":["Reactive Programming","Libs","Swift","Uncategorized","Open source projects","Events [🔝](#readme)"],"sub_categories":["React-Like","Events","Uncategorized","Other free courses"],"readme":"\n![Katana](https://raw.githubusercontent.com/BendingSpoons/katana-swift/master/.github/Assets/katana_header.png)\n\n[![Twitter URL](https://img.shields.io/twitter/url/https/twitter.com/fold_left.svg?style=social\u0026label=Follow%20katana_swift)](https://twitter.com/katana_swift)\n[![Build Status](https://github.com/BendingSpoons/katana-swift/workflows/Build%20and%20Test/badge.svg)](https://github.com/BendingSpoons/katana-swift/actions/workflows/build_and_test.yml)\n[![Docs](https://img.shields.io/cocoapods/metrics/doc-percent/Katana.svg)]()\n[![CocoaPods](https://img.shields.io/cocoapods/v/Katana.svg)]()\n[![Licence](https://img.shields.io/badge/Licence-MIT-lightgrey.svg)](https://github.com/BendingSpoons/katana-swift/blob/master/LICENSE)\n\nKatana is a modern Swift framework for writing iOS applications' business logic that are testable and easy to reason about. Katana is strongly inspired by [Redux](http://redux.js.org/).\n\nIn few words, the app state is entirely described by a single serializable data structure, and the only way to change the state is to dispatch a `StateUpdater`. A `StateUpdater` is an intent to transform the state, and contains all the information to do so. Because all the changes are centralized and are happening in a strict order, there are no subtle race conditions to watch out for.\n\nWe feel that Katana helped us a lot since we started using it in production. Our applications have been downloaded several millions of times and Katana really helped us scaling them quickly and efficiently. [Bending Spoons](http://www.bendingspoons.com)'s engineers leverage Katana capabilities to design, implement and test complex applications very quickly without any compromise to the final result. \n\nWe use a lot of open source projects ourselves and we wanted to give something back to the community, hoping you will find this useful and possibly contribute. ❤️\n\n## State of the project\n\nWe wrote several successful applications using the layer that `Katana` and `Tempura` provide. We still think that their approach is really a good one for medium-sized applications but, as our app grows, it becomes increasingly important to have a more modular architecture. For this reason, we have migrated our applications to use [The Composable Architecture](https://github.com/pointfreeco/swift-composable-architecture).\n\n## Overview\n\nYour entire app `State` is defined in a single struct, all the relevant application information should be placed here.\n\n```swift\nstruct CounterState: State {\n  var counter: Int = 0\n}\n```\n\nThe app `State` can only be modified by a `StateUpdater`. A `StateUpdater` represents an event that leads to a change in the `State` of the app. You define the behaviour of the `State Updater` by implementing the `updateState(:)` method that changes the `State` based on the current app `State` and the `StateUpdater` itself. The `updateState` should be a pure function, which means that it only depends on the inputs (that is, the state and the state updater itself) and it doesn't have side effects, such as network interactions.\n\n```swift\nstruct IncrementCounter: StateUpdater {\n  func updateState(_ state: inout CounterState) {\n    state.counter += 1\n  }\n}\n```\n\nThe `Store` contains and manages your entire app `State`. It is responsible of managing the dispatched items (e.g., the just mentioned `State Updater`).\n\n```swift\n// ignore AppDependencies for the time being, it will be explained later on\nlet store = Store\u003cCounterState, AppDependencies\u003e()\nstore.dispatch(IncrementCounter())\n```\n\nYou can ask the `Store` to be notified about every change in the app `State`.\n\n```swift\nstore.addListener() { oldState, newState in\n  // the app state has changed\n}\n```\n\n## Side Effects\n\nUpdating the application's state using pure functions is nice and it has a lot of benefits. Applications have to deal with the external world though (e.g., API call, disk files management, …). For all this kind of operations, Katana provides the concept of `side effects`. Side effects can be used to interact with other parts of your applications and then dispatch new `StateUpdater`s to update your state. For more complex situations, you can also dispatch other `side effects`.\n\n`Side Effect`s are implemented on top of [Hydra](https://github.com/malcommac/Hydra/), and allow you to write your logic using [promises](https://promisesaplus.com/). In order to leverage this functionality you have to adopt the `SideEffect` protocol\n\n```swift\nstruct GenerateRandomNumberFromBackend: SideEffect {\n  func sideEffect(_ context: SideEffectContext\u003cCounterState, AppDependencies\u003e) throws {\n    // invokes the `getRandomNumber` method that returns a promise that is fullfilled\n    // when the number is received. At that point we dispatch a State Updater\n    // that updates the state\n    context.dependencies.APIManager\n        .getRandomNumber()\n        .then { randomNumber in context.dispatch(SetCounter(newValue: randomNumber)) }\n  }\n}\n\nstruct SetCounter: StateUpdater {\n  let newValue: Int\n  \n  func updateState(_ state: inout CounterState) {\n    state.counter = self.newValue\n  }\n}\n```\n\n Moreover, you can leverage the `Hydra.await` operator to write logic that mimics the [async/await](https://github.com/tc39/ecmascript-asyncawait) pattern, which allows you to write async code in a sync manner.\n\n```swift\nstruct GenerateRandomNumberFromBackend: SideEffect {\n  func sideEffect(_ context: SideEffectContext\u003cCounterState, AppDependencies\u003e) throws {\n    // invokes the `getRandomNumber` method that returns a promise that is fulfilled\n    // when the number is received.\n    let promise = context.dependencies.APIManager.getRandomNumber()\n    \n    // we use Hydra.await to wait for the promise to be fulfilled\n    let randomNumber = try Hydra.await(promise)\n\n    // then the state is updated using the proper state updater\n    try Hydra.await(context.dispatch(SetCounter(newValue: randomNumber)))\n  }\n}\n```\n\nIn order to further improve the usability of side effects, there is also a version which can return a value. Note that both the state and dependencies types are erased, to allow for more freedom when using it in libraries, for example.\n\n```swift\nstruct PurchaseProduct: ReturningSideEffect {\n  let productID: ProductID\n\n  func sideEffect(_ context: AnySideEffectContext) throws -\u003e Result\u003cPurchaseResult, PurchaseError\u003e {\n\n    // 0. Get the typed version of the context\n    guard let context = context as? SideEffectContext\u003cCounterState, AppDependencies\u003e else {\n      fatalError(\"Invalid context type\")\n    }\n\n    // 1. purchase the product via storekit\n    let storekitResult = context.dependencies.monetization.purchase(self.productID)\n    if case .failure(let error) = storekitResult {\n      return .storekitRejected(error)\n    }\n\n    // 2. get the receipt\n    let receipt = context.dependencies.monetization.getReceipt()\n\n    // 3. validate the receipt\n    let validationResult = try Hydra.await(context.dispatch(Monetization.Validate(receipt)))\n\n    // 4. map error\n    return validationResult\n      .map { .init(validation: $0) }\n      .mapError { .validationRejected($0) }\n  }\n}\n```\n\nNote that, if this is a prominent use case for the library/app, the step `0` can be encapsulated in a protocol like this:\n\n```swift\nprotocol AppReturningSideEffect: ReturningSideEffect {\n  func sideEffect(_ context: SideEffectContext\u003cAppState, DependenciesContainer\u003e) -\u003e Void\n}\n\nextension AppReturningSideEffect {\n  func sideEffect(_ context: AnySideEffectContext) throws -\u003e Void {\n    guard let context = context as? SideEffectContext\u003cAppState, DependenciesContainer\u003e else {\n      fatalError(\"Invalid context type\")\n    }\n    \n    self.sideEffect(context)\n  }\n}\n```\n\n#### Dependencies\n\nThe side effect example leverages an `APIManager` method. The `Side Effect` can get the `APIManager` by using the `dependencies` parameter of the context.  The `dependencies container` is the Katana way of doing dependency injection. We test our side effects, and because of this we need to get rid of singletons or other bad pratices that prevent us from writing tests. Creating a dependency container is very easy: just create a class that conforms to the `SideEffectDependencyContainer` protocol, make the store generic to it, and use it in the side effect.\n\n```swift\nfinal class AppDependencies: SideEffectDependencyContainer {\n  required init(dispatch: @escaping PromisableStoreDispatch, getState: @escaping GetState) {\n\t\t// initialize your dependencies here\n\t}\n}\n```\n\n## Interceptors\n\nWhen defining a `Store` you can provide a list of interceptors that are triggered in the given order whenever an item is dispatched. An interceptor is like a catch-all system that can be used to implement functionalities such as logging or to dynamically change the behaviour of the store. An interceptor is invoked every time a dispatchable item is about to be handled.\n\n#### DispatchableLogger\n Katana comes with a built-in `DispatchableLogger` interceptor that logs all the dispatchables, except the ones listed in the blacklist parameter.\n\n```swift\nlet dispatchableLogger = DispatchableLogger.interceptor(blackList: [NotToLog.self])\nlet store = Store\u003cCounterState\u003e(interceptor: [dispatchableLogger])\n```\n\n#### ObserverInterceptor\nSometimes it is useful to listen for events that occur in the system and react to them. Katana provides the `ObserverInterceptor` that can be used to achieve this result.\n\nIn particular you instruct the interceptor to dispatch items when:\n\n* the store is initialized\n* the state changes in a particular way\n* a particular dispatchable item is managed by the store\n* a particular notification is sent to the default [NotificationCenter](https://developer.apple.com/documentation/foundation/nsnotificationcenter)\n\n```swift\nlet observerInterceptor = ObserverInterceptor.observe([\n  .onStart([\n    // list of dispatchable items dispatched when the store is initialized\n  ])\n])\n\nlet store = Store\u003cCounterState\u003e(interceptor: [observerInterceptor])\n```\n\nNote that when intercepting a side effect using an `ObserverInterceptor`, the return value of the dispatchable is not available to the interceptor itself.\n\n## What about the UI?\n\nKatana is meant to give structure to the logic part of your app. When it comes to UI we propose two alternatives:\n\n- [Tempura](https://github.com/BendingSpoons/tempura-swift): an MVVC framework we built on top of Katana and that we happily use to develop the UI of all our apps at Bending Spoons.  Tempura is a lightweight, UIKit-friendly library that allows you to keep the UI automatically in sync with the state of your app. This is our suggested choice.\n\n- [Katana-UI](https://github.com/BendingSpoons/katana-ui-swift): With this library, we aimed to port React to UIKit, it allows you to create your app using a declarative approach. The library was initially bundled together with Katana, we decided to split it as internally we don't use it anymore. In retrospect, we found that the impedance mismatch between the React-like approach and the imperative reality of UIKit was a no go for us.\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://github.com/BendingSpoons/tempura-swift\"\u003e\u003cimg src=\"https://raw.githubusercontent.com/BendingSpoons/katana-swift/master/.github/Assets/tempura.png\" alt=\"Tempura\" width=\"240\" /\u003e\u003c/a\u003e\n  \u003ca href=\"https://github.com/BendingSpoons/katana-ui-swift\"\u003e\u003cimg src=\"https://raw.githubusercontent.com/BendingSpoons/katana-swift/master/.github/Assets/katanaUI.png\" alt=\"Katana UI\" width=\"240\" /\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n## Signpost Logger\n\nKatana is automatically integrated with the [Signpost API](https://developer.apple.com/documentation/os/ossignpostid). This integration layer allows you to see in Instruments all the items that have been dispatched, how long they last, and useful pieces of information such as the parallelism degree. Moreover, you can analyse the cpu impact of the items you dispatch to furtherly optimise your application performances.\n\n![](https://raw.githubusercontent.com/BendingSpoons/katana-swift/master/.github/Assets/signpost.jpg)\n\n## Bending Spoons Guidelines\n\nIn Bending Spoons, we are extensively using Katana. In these years, we've defined some best pratices that have helped us write more readable and easier to debug code. We've decided to open source them so that everyone can have a starting point when using Katana. You can find them [here](https://github.com/BendingSpoons/katana-swift/blob/master/BSP_GUIDELINES.md).\n\n## Migration from 2.x\n\nWe strongly suggest to upgrade to the new Katana. The new Katana, in fact, not only adds new very powerful capabilities to the library, but it has also been designed to be extremely compatible with the old logic. All the actions and middleware you wrote for Katana 2.x, will continue to work in the new Katana as well. The breaking changes are most of the time related to simple typing changes that are easily addressable.\n\nIf you prefer to continue with Katana 2.x, however, you can still access Katana 2.x in the [dedicated branch](https://github.com/BendingSpoons/katana-swift/tree/2.x).\n\n### Middleware\nIn Katana, the concept of `middleware` has been replaced with the new concept of `interceptor`. You can still use your middleware by leveraging the `middlewareToInterceptor` method.\n\n## Swift Version\nCertain versions of Katana only support certain versions of Swift. Depending on which version of Swift your project is using, you should use specific versions of Katana.\nUse this table in order to check which version of Katana you need.\n\n| Swift Version  | Katana Version |\n| -------------- | -------------- |\n| Swift 5.0      | Katana \u003e= 6.0  |\n| Swift 4.2      | Katana \u003e= 2.0  |\n| Swift 4.1      | Katana \u003c 2.0   |\n\n\n## Where to go from here\n\n### Give it a shot\n\n```\npod try Katana\n```\n\n### Tempura\n\nMake awesome applications using Katana together with [Tempura](https://github.com/BendingSpoons/tempura-lib-swift)\n\n### Check out the documentation\n\n[Documentation](http://katana.bendingspoons.com)\n\nYou can also add Katana to [Dash](https://kapeli.com/dash) using the proper [docset](https://github.com/BendingSpoons/katana-swift/blob/master/docs/latest/docsets/Katana.tgz?raw=true).\n\n## Installation\n\nKatana is available through [CocoaPods](https://cocoapods.org/) and [Swift Package Manager](https://swift.org/package-manager/), you can also drop `Katana.project` into your Xcode project.\n\n### Requirements\n\n- iOS 11.0+ / macOS 10.10+\n\n- Xcode 9.0+\n\n- Swift 5.0+\n\n### Swift Package Manager\n[Swift Package Manager](https://swift.org/package-manager/) is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.\n\nThere are two ways to integrate Katana in your project using Swift Package Manager:\n- Adding it to your `Package.swift`\n- Adding it directly from Xcode under `File` -\u003e `Swift Packages` -\u003e `Add Package dependency..`\n\nIn both cases you only need to provide this URL: `git@github.com:BendingSpoons/katana-swift.git`\n\n### CocoaPods\n\n [CocoaPods](https://cocoapods.org/) is a dependency manager for Cocoa projects. You can install it with the following command:\n\n```bash\n$ sudo gem install cocoapods\n```\n\nTo integrate Katana into your Xcode project using CocoaPods you need to create a `Podfile`.\n\nFor iOS platforms, this is the content\n\n```ruby\nuse_frameworks!\nsource 'https://github.com/CocoaPods/Specs.git'\nplatform :ios, '9.0'\n\ntarget 'MyApp' do\n  pod 'Katana'\nend\n```\n\nNow, you just need to run:\n\n```bash\n$ pod install\n```\n\n## Get in touch \n\n- if you have __any questions__ you can find us on twitter: [@maurobolis](https://twitter.com/maurobolis), [@luca_1987](https://twitter.com/luca_1987), [@smaramba](https://twitter.com/smaramba)\n\n## Special thanks\n\n- [Everyone at Bending Spoons](http://bendingspoons.com/team.html) for providing their priceless input;\n- [@orta](https://twitter.com/orta) for providing input on how to opensource the project;\n- [@danielemargutti](https://twitter.com/danielemargutti/) for developing and maintaining [Hydra](https://github.com/malcommac/Hydra/);\n\n## Contribute\n\n- If you've __found a bug__, open an issue;\n- If you have a __feature request__, open an issue;\n- If you __want to contribute__, submit a pull request;\n- If you __have an idea__ on how to improve the framework or how to spread the word, please [get in touch](#get-in-touch);\n- If you want to __try the framework__ for your project or to write a demo, please send us the link of the repo.\n\n\n## License\n\nKatana is available under the [MIT license](https://github.com/BendingSpoons/katana-swift/blob/master/LICENSE).\n\n## About\n\nKatana is maintained by Bending Spoons.\nWe create our own tech products, used and loved by millions all around the world.\nInterested? [Check us out](http://bndspn.com/2fKggTa)!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBendingSpoons%2Fkatana-swift","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FBendingSpoons%2Fkatana-swift","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBendingSpoons%2Fkatana-swift/lists"}