{"id":15787170,"url":"https://github.com/fmo91/microfutures","last_synced_at":"2025-05-08T07:36:59.726Z","repository":{"id":62447785,"uuid":"80242055","full_name":"fmo91/Microfutures","owner":"fmo91","description":"Lightweight implementation of Futures that shares a similar subscription interface with RxSwift.","archived":false,"fork":false,"pushed_at":"2017-01-29T06:01:08.000Z","size":37,"stargazers_count":38,"open_issues_count":0,"forks_count":3,"subscribers_count":5,"default_branch":"master","last_synced_at":"2024-10-11T21:45:08.046Z","etag":null,"topics":["chaining-futures","ios","lightweight","promises","swift"],"latest_commit_sha":null,"homepage":"https://fmo91.github.io/Microfutures/","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/fmo91.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-01-27T20:09:17.000Z","updated_at":"2021-09-11T06:36:03.000Z","dependencies_parsed_at":"2022-11-01T23:06:14.256Z","dependency_job_id":null,"html_url":"https://github.com/fmo91/Microfutures","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fmo91%2FMicrofutures","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fmo91%2FMicrofutures/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fmo91%2FMicrofutures/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fmo91%2FMicrofutures/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fmo91","download_url":"https://codeload.github.com/fmo91/Microfutures/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253024094,"owners_count":21842396,"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":["chaining-futures","ios","lightweight","promises","swift"],"created_at":"2024-10-04T21:06:02.593Z","updated_at":"2025-05-08T07:36:59.696Z","avatar_url":"https://github.com/fmo91.png","language":"Swift","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Microfutures\n\n[![CI Status](http://img.shields.io/travis/Fernando Ortiz/Microfutures.svg?style=flat)](https://travis-ci.org/Fernando Ortiz/Microfutures)\n[![Version](https://img.shields.io/cocoapods/v/Microfutures.svg?style=flat)](http://cocoapods.org/pods/Microfutures)\n[![License](https://img.shields.io/cocoapods/l/Microfutures.svg?style=flat)](http://cocoapods.org/pods/Microfutures)\n[![Platform](https://img.shields.io/cocoapods/p/Microfutures.svg?style=flat)](http://cocoapods.org/pods/Microfutures)\n\n## Introduction\nMicrofutures is a very small library (60 LOCs) that implements a simple Futures/Promises flow. It also has a similar public interface to [RxSwift](https://github.com/ReactiveX/RxSwift). \n\n## What is a future?\nA future is a representation of a value that hasn't been already generated. The best use case of Futures is to simplify an asynchronous flow. Instead of writing nested callbacks, you can chain futures, turning that awful callback hell into a beautiful functional pipeline.\n\n## In a glance\n\nMicrofutures lets you turn from this:\n\n```swift\ngetUser(withID: 3) { user, error in\n\tif let error = error {\n\t\tprint(\"An error ocurred\") \n    } else if let user = user {\n    \tself.getPosts(forUserID: user.id) { posts, error in\n        \tif let error = error {\n            \tprint(\"An error ocurred\")\n            } else if let posts = posts {\n            \tif let firstPost = posts.first {\n                \tself.getComments(forPostID: firstPost.id) { error, comments in\n                    \tif let error = error {\n\t\t\t            \tprint(\"An error ocurred\")\n                        } else if let comments = comments {\n                        \tprint(\"Comments count: \\(comments.count)\")\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n```\n\n(And I am not exaggerating here, this is a pretty common scenario, and everyone is guilty for writing something like this at least once.)\n\nTo this:\n\n```swift\ngetUser(withID: 3)\n\t.flatMap(getPosts)\n    .map { posts in return posts.first?.id }\n    .flatMap(getComments)\n    .map { comments in return comments.count }\n    .subscribe (\n    \tonNext: { commentsCount in\n        \tprint(\"Comments count: \\(commentsCount)\")\n        }, \n        onError: { error in\n        \tprint(\"An error ocurred.\")\n        }\n    )\n```\n\nMuch cleaner.\n\n## Creating a future\nCreating a future couldn't be simpler.\n\nLets compare how you write a callback based async function vs a future based async function.\n\n```swift\n// Callback based func:\nfunc getUser(withID id: Int, completion: (Error?, User?) -\u003e Void) {\n\tAPIClient\n    \t// This api client also works using callbacks\n\t    .get(\"https://somecoolapi.com/users/\\(id)\") { error, json in \n        \tif let error = error {\n            \tcompletion(error, nil)\n                return\n            } else {\n            \tguard let json = json else {\n                \tcompletion(NetworkingError.emptyResponse, nil)\n                    return\n                }\n                guard let user = User(json: json) else {\n                \tcompletion(NetworkingError.invalidReponse, nil)\n                    return\n                }\n                completion(nil, user)\n            }\n        }\n} \n```\n\nHere is the future based async function:\n\n```swift\nfunc getUser(withID id: Int) -\u003e Future\u003cUser\u003e {\n\treturn Future { completion in\n    \tAPIClient\n        \t// Imagine that this api client still uses a callback based approach.\n        \t.get(\"https://somecoolapi.com/users/\\(id)\") { error, json in\n            \tif let error = error {\n                    completion(.failure(error))\n                    return\n                } else {\n                    guard let json = json else {\n                        completion(.failure(NetworkingError.emptyResponse))\n                        return\n                    }\n                    guard let user = User(json: json) else {\n                        completion(.failure(NetworkingError.invalidReponse))\n                        return\n                    }\n                    completion(.success(user))\n                }\n\t\t\t}\n    }\n}\n```\n\nYes, it's exactly the same. But that's because our API Client still uses a callback based approach.\n\nOne of the strong points of using a Futures based approach is that you can use functional tools. Compare the previous snippet with this:\n\n```swift\nfunc getUser(withID id: Int) -\u003e Future\u003cUser\u003e {\n\treturn APIClient\n    \t.get(\"https://somecoolapi.com/users/\\(id)\")\n        .map { json in\n            guard let user = User(json: json) else {\n                throw NetworkingError.invalidReponse\n            }\n            completion(.success(user))\n        }\n}\n```\n\nAs I will explain later, the `map` function transforms the `Future` value to another value. In this case, `map` transforms the json value to a User object.\n\n## Transforming Future's value using map\n`map` transforms the output of a Future in another value.\n\nFor example:\n\n```swift\ngetAlbum(withID: 3)\n\t.map { album in\n    \treturn album.title\n    }\n    .map { albumTitle in\n    \treturn \"THe album title is \\(albumTitle)\"\n    }\n    // ...\n```\n\nAn important thing about `map` is that it won't be executed if the future contains an error.\n\n`map` can also throw an error if it's necessary:\n\n```swift\ngetUser(withID: 3)\n\t.map { user in\n    \tguard let mobile = user.mobilePhone else {\n        \tthrow UserError.noMobileNumber\n        }\n        return mobile\n    }\n```\n\n## Chaining Futures using flatMap\n\nSometimes you want to perform an async function after another async function. This often results in a callback hell.\nFutures has a solution for that, and it's using `flatMap`\n\n`flatMap` receives a function that transforms the output value of the future and returns another future.\n\nFor example:\n\n```swift\n\nfunc getPosts(forUserID userID: Int) -\u003e Future\u003c[Post]\u003e {\n\treturn APIClient\n    \t.get(\"https://somecoolapi.com/posts?userID=\\(userID)\")\n        .map { json in\n        \tguard let jsonArray = json as? [JSON] else {\n            \tthrow NetworkingError.invalidReponse\n            }\n        \treturn jsonArray.map(Post.init)\n        }\n}\n\ngetUser(withID: 3)\n\t.flatMap { user in\n    \treturn getPosts(forUserID: user.id)\n    }\n    \n// Or doing this\ngetUser(withID: 3)\n\t.map { user in return user.id }\n\t.flatMap (getPosts)\n```\n\n## Resolving Futures\n\nThe last step is subscribing to the `Future`. It's achieved by using the `subscribe` method.\n\nFor example:\n\n```swift\ngetUser(withID: 3)\t\n\t.map { user in return user.id }\n\t.flatMap (getPosts)\n\t.subscribe( \n    \tonNext: { posts in\n\t\t\t// Do something with posts...\n        },\n        onError: { error in\n        \t// Handle this error.\n        }\n    )\n```\n\nSubscribe receives two functions, one for the happy path, and another for the wrong case.\n\n`onNext` is a function that receives the `Future` value and performs something with that value.\n\n`onError` is a function that receives an error and handles it.\n\n## Similarity with RxSwift\n\n`Future` methods names has been chosen following RxSwift names. `map`, `flatMap`, and `subscribe` are names that RxSwift uses, and this library can be used as an introduction for somebody to RxSwift terms.\n\n## Example\n\nTo run the example project, clone the repo, and run `pod install` from the Example directory first.\n\n## Installation\n\nMicrofutures is available through [CocoaPods](http://cocoapods.org). To install\nit, simply add the following line to your Podfile:\n\n```ruby\npod \"Microfutures\"\n```\n\nOr you can just copy and paste `Microfutures.swift` into your project.\n\n## Author\n\nFernando Ortiz, ortizfernandomartin@gmail.com\n\n## License\n\nMicrofutures is available under the MIT license. See the LICENSE file for more info.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffmo91%2Fmicrofutures","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffmo91%2Fmicrofutures","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffmo91%2Fmicrofutures/lists"}