All Projects → fmo91 → Microfutures

fmo91 / Microfutures

Licence: MIT license
Lightweight implementation of Futures that shares a similar subscription interface with RxSwift.

Programming Languages

swift
15916 projects
ruby
36898 projects - #4 most used programming language

Projects that are alternatives of or similar to Microfutures

Yaku
A lightweight promise library
Stars: ✭ 276 (+626.32%)
Mutual labels:  lightweight, promises
query2report
Query2Report is a simple open source business intelligence platform that allows users to build report/dashboard for business analytics or enterprise reporting
Stars: ✭ 43 (+13.16%)
Mutual labels:  lightweight
node-pagerduty
⛔️ DEPRECATED - PagerDuty v2 API Wrapper for Node
Stars: ✭ 19 (-50%)
Mutual labels:  promises
d2launcher
Diablo II • Median XL • Mod Launcher for Linux
Stars: ✭ 20 (-47.37%)
Mutual labels:  lightweight
canorus
Canorus is a free cross-platform music score editor
Stars: ✭ 25 (-34.21%)
Mutual labels:  lightweight
XYFSnowAnimation
A category of NSTimer for showing 3D Fluttered animation for iOS, which is used very simply. Lightweight CALayer animation, core animation, 3D transform, performance safety. iOS 3D三维飘落下雪落花动画,轻量级CALayer图层动画,核心动画,3D形变,性能安全,定时器NSTimer分类,直接使用,很简单
Stars: ✭ 15 (-60.53%)
Mutual labels:  lightweight
node-pg-large-object
Large object support for PostgreSQL clients using the node-postgres library.
Stars: ✭ 31 (-18.42%)
Mutual labels:  promises
rust-xoodyak
Xoodyak, a lightweight and versatile cryptographic scheme implemented in Rust.
Stars: ✭ 28 (-26.32%)
Mutual labels:  lightweight
vue-promise-dialogs
A tiny & modern library that allows you to work with dialogs as with asynchronous functions.
Stars: ✭ 43 (+13.16%)
Mutual labels:  promises
go-baseapp
A lightweight starting point for Go web servers
Stars: ✭ 61 (+60.53%)
Mutual labels:  lightweight
tb-grid
tb-grid is a super simple and lightweight 12 column responsive grid system utilizing css grid.
Stars: ✭ 19 (-50%)
Mutual labels:  lightweight
vim-config
My .vimrc config
Stars: ✭ 20 (-47.37%)
Mutual labels:  lightweight
Rakkit
🌐 A framework written in TypeScript that provides REST/GraphQL API and Websocket tools to build amazing server-side applications
Stars: ✭ 32 (-15.79%)
Mutual labels:  lightweight
hat-view
Allow to put "hat" on TextView. Inspired by Telegram appbar title with Santa Claus hat 🎅🏻
Stars: ✭ 51 (+34.21%)
Mutual labels:  lightweight
sgo
A simple, light and fast Web framework written in Go.
Stars: ✭ 75 (+97.37%)
Mutual labels:  lightweight
cli
a lightweight and simple cli package
Stars: ✭ 12 (-68.42%)
Mutual labels:  lightweight
i18n-core
i18n-core is a no-fuzz Node.js implementation of i18n.
Stars: ✭ 14 (-63.16%)
Mutual labels:  lightweight
plexydesk
Lightweight Desktop Manager for Gnu/Linux and FreeBSD - Ideal for Low resource computers
Stars: ✭ 33 (-13.16%)
Mutual labels:  lightweight
MatrixLib
Lightweight header-only matrix library (C++) for numerical optimization and machine learning. Contact me if there is an exciting opportunity.
Stars: ✭ 35 (-7.89%)
Mutual labels:  lightweight
jeelizGlanceTracker
JavaScript/WebGL lib: detect if the user is looking at the screen or not from the webcam video feed. Lightweight and robust to all lighting conditions. Great for play/pause videos if the user is looking or not, or for person detection. Link to live demo.
Stars: ✭ 68 (+78.95%)
Mutual labels:  lightweight

Microfutures

[![CI Status](http://img.shields.io/travis/Fernando Ortiz/Microfutures.svg?style=flat)](https://travis-ci.org/Fernando Ortiz/Microfutures) Version License Platform

Introduction

Microfutures is a very small library (60 LOCs) that implements a simple Futures/Promises flow. It also has a similar public interface to RxSwift.

What is a future?

A 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.

In a glance

Microfutures lets you turn from this:

getUser(withID: 3) { user, error in
	if let error = error {
		print("An error ocurred") 
    } else if let user = user {
    	self.getPosts(forUserID: user.id) { posts, error in
        	if let error = error {
            	print("An error ocurred")
            } else if let posts = posts {
            	if let firstPost = posts.first {
                	self.getComments(forPostID: firstPost.id) { error, comments in
                    	if let error = error {
			            	print("An error ocurred")
                        } else if let comments = comments {
                        	print("Comments count: \(comments.count)")
                        }
                    }
                }
            }
        }
    }
}

(And I am not exaggerating here, this is a pretty common scenario, and everyone is guilty for writing something like this at least once.)

To this:

getUser(withID: 3)
	.flatMap(getPosts)
    .map { posts in return posts.first?.id }
    .flatMap(getComments)
    .map { comments in return comments.count }
    .subscribe (
    	onNext: { commentsCount in
        	print("Comments count: \(commentsCount)")
        }, 
        onError: { error in
        	print("An error ocurred.")
        }
    )

Much cleaner.

Creating a future

Creating a future couldn't be simpler.

Lets compare how you write a callback based async function vs a future based async function.

// Callback based func:
func getUser(withID id: Int, completion: (Error?, User?) -> Void) {
	APIClient
    	// This api client also works using callbacks
	    .get("https://somecoolapi.com/users/\(id)") { error, json in 
        	if let error = error {
            	completion(error, nil)
                return
            } else {
            	guard let json = json else {
                	completion(NetworkingError.emptyResponse, nil)
                    return
                }
                guard let user = User(json: json) else {
                	completion(NetworkingError.invalidReponse, nil)
                    return
                }
                completion(nil, user)
            }
        }
} 

Here is the future based async function:

func getUser(withID id: Int) -> Future<User> {
	return Future { completion in
    	APIClient
        	// Imagine that this api client still uses a callback based approach.
        	.get("https://somecoolapi.com/users/\(id)") { error, json in
            	if let error = error {
                    completion(.failure(error))
                    return
                } else {
                    guard let json = json else {
                        completion(.failure(NetworkingError.emptyResponse))
                        return
                    }
                    guard let user = User(json: json) else {
                        completion(.failure(NetworkingError.invalidReponse))
                        return
                    }
                    completion(.success(user))
                }
			}
    }
}

Yes, it's exactly the same. But that's because our API Client still uses a callback based approach.

One of the strong points of using a Futures based approach is that you can use functional tools. Compare the previous snippet with this:

func getUser(withID id: Int) -> Future<User> {
	return APIClient
    	.get("https://somecoolapi.com/users/\(id)")
        .map { json in
            guard let user = User(json: json) else {
                throw NetworkingError.invalidReponse
            }
            completion(.success(user))
        }
}

As 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.

Transforming Future's value using map

map transforms the output of a Future in another value.

For example:

getAlbum(withID: 3)
	.map { album in
    	return album.title
    }
    .map { albumTitle in
    	return "THe album title is \(albumTitle)"
    }
    // ...

An important thing about map is that it won't be executed if the future contains an error.

map can also throw an error if it's necessary:

getUser(withID: 3)
	.map { user in
    	guard let mobile = user.mobilePhone else {
        	throw UserError.noMobileNumber
        }
        return mobile
    }

Chaining Futures using flatMap

Sometimes you want to perform an async function after another async function. This often results in a callback hell. Futures has a solution for that, and it's using flatMap

flatMap receives a function that transforms the output value of the future and returns another future.

For example:

func getPosts(forUserID userID: Int) -> Future<[Post]> {
	return APIClient
    	.get("https://somecoolapi.com/posts?userID=\(userID)")
        .map { json in
        	guard let jsonArray = json as? [JSON] else {
            	throw NetworkingError.invalidReponse
            }
        	return jsonArray.map(Post.init)
        }
}

getUser(withID: 3)
	.flatMap { user in
    	return getPosts(forUserID: user.id)
    }
    
// Or doing this
getUser(withID: 3)
	.map { user in return user.id }
	.flatMap (getPosts)

Resolving Futures

The last step is subscribing to the Future. It's achieved by using the subscribe method.

For example:

getUser(withID: 3)	
	.map { user in return user.id }
	.flatMap (getPosts)
	.subscribe( 
    	onNext: { posts in
			// Do something with posts...
        },
        onError: { error in
        	// Handle this error.
        }
    )

Subscribe receives two functions, one for the happy path, and another for the wrong case.

onNext is a function that receives the Future value and performs something with that value.

onError is a function that receives an error and handles it.

Similarity with RxSwift

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.

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

Installation

Microfutures is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "Microfutures"

Or you can just copy and paste Microfutures.swift into your project.

Author

Fernando Ortiz, [email protected]

License

Microfutures is available under the MIT license. See the LICENSE file for more info.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].