Code Monkey home page Code Monkey logo

futurekit's Introduction

FutureKit for Swift

CocoaPods Compatible Carthage Compatible License Platform Twitter

A Swift based Future/Promises Library for IOS and OS X.

Note - The latest FutureKit is works 3.0

For Swift 2.x compatibility use version 2.3.0

FutureKit is a Swift implementation of Futures and Promises, but modified specifically for iOS/OSX programmers. You can ready the wikipedia article here: http://en.wikipedia.org/wiki/Futures_and_promises

FutureKit uses Swift generic classes, to allow you to easily deal with asynchronous/multi-threaded issues when coding for iOS or OSX.

  • is 100% Swift. It currently supports Swift 2.x/3.0 and Xcode 8+. For Swift 2.x compatibility, use the version 2.3.0.

  • is type safe. It uses Swift Generics classes that can automatically infer the type you wish to return from asynchronous logic. And supports both value and reference Swift types (Both 'Any' types, and 'AnyObject/NSObject' types.)

  • Is Swift error handling friendly. All FutureKit handler methods can already catch and complete a Future using any ErrorType. So you don't need to wrap your code with 'do/try/catch'.

  • FutureKit in Swift is designed to simplify error handling, allowing you to attach a single error handler that can catch any error that may occur. This can make dealing with composing async operations much easier and more reliable.

  • uses simple to understand methods (onComplete/onSuccess/onFail etc) that let's you simplify complex asynchronous operations into clear and simple to understand logic.

  • is highly composeable, since any existing Future can be used to generate a new Future. And Errors and Cancelations can be automatically passed through, simplifying error handling logic.

  • Super easy cancelation composition (which is a fancy way to say cancel works when you want it to automatically). Future's are designed so there is never any confusion about whether an asynchronous operation completed, failed, or was canceled. And the consumer has full control over whether he needs to be notified that the operation was canceled or not. (0% confusion about whether your completion blocks will get called when the operation is cancelled).

  • works well editing code within Xcode auto-completion. The combination of type-inference and code-completion makes FutureKit coding fast and easy.

  • simplifies the use of Apple GCD by using Executors - a simple Swift enumeration that simplifies the most common iOS/OSX Dispatch Queues (Main,Default,Background, etc). Allowing you to guarantee that logic will always be executed in the context you want. (You never have to worry about having to call the correct dispatch_async() function again).

  • is highly tunable, allowing you to configure how the primary Executors (Immediate vs Async) execute, and what sort Thread Synchronization FutureKit will use (Barriers - Locks, etc). Allowing you to tune FutureKit's logic to match what you need.

What the Heck is a Future?

So the simple answer is that Future is an object that represents that you will get something in the future. Usually from another process possible running in another thread. Or maybe a resource that needs to loaded from an external server.

let imageView : UIImageView =  // some view on my view controller.
let imageFuture : Future<UIImage> = MyApiClass().getAnImageFromServer()

There are few things that are interesting. This object represents both that an image will arrive, and it will give me universal way to handle failures and cancellation. It could be that MyApiClass() is using NSURLSessions, or AlamoFire, combined with some kinda cool image cache based on SDWebImage. But this viewController doesn't care. Just give me a Future<UIImage>. Somehow.

now I can do this:

imageFuture.onSuccess(.Main) {  image  in
    imageView.image = image
}

This is a quick way of saying "when it's done, on the MainQ, set the image to an ImageView.

Let's make things more interesting. Now your designer tell you he wants you to add a weird Blur effect to the image. Which means you have to add an UIImage effect. Which you better not do compute in the MainQ cause it's mildly expensive.

So know you have two asynchronous dependencies, one async call for the network, and another for the blur effect. In traditional iOS that would involve a lot of custom block handlers for different API, and handling dispatch_async calls.

Instead we are gonna do this.

let imageFuture : Future<UIImage> = MyApiClass().getAnImageFromServer()
let blurImageFuture =  imageFuture.onSuccess(.UserInitiated) { (image) -> UIImage in
     let blurredImage = doBlurEffect(image)
     return blurredImage
}

blurrImageFuture is now a NEW Future. That I have created from imageFuture. I also defined I want that block to run in the .UserInitiated dispatch queue. (Cause I need it fast!).

blurImageFuture.onSuccess(.Main) { (blurredImage) -> Void in
     imageView.image = blurredImage;
}

Or I could rewite it all in one line:

MyApiClass().getAnImageFromServer()
     .onSuccess(.UserInitiated) { (image) -> UIImage in {
                    let blurredImage = doBlurEffect(image)
                    return blurredImage
     }.onSuccess(.Main) { (blurredImage) -> Void in
                     imageView.image = blurredImage;
     }.onError { error in
                 // deal with any error that happened along the way
     }

That's the QUICK 1 minute answer of what this can do. It let's you take any asynchronous operation and "map" it into a new one. So you can take all your APIs and background logic and get them to easily conform to a universal way of interacting. Which can let you get away with a LOT of crazy asynchronous execution, without giving up stability and ease of understanding.

Plus it's all type safe. You could use handler to convert say, an Future<NSData> from your API server into a Future<[NSObject:AnyObject]> holding the JSON. And than map that to a Future<MyDatabaseEntity> after it's written to a database.

It's a neat way to stitch all your Asynchronous issues around a small set of classes.

Then what is a Promise?

A promise is a way for you write functions that returns Futures.

func getAnImageFromServer(url : NSURL) -> Future<UIImage> {
    let p = Promise<UIImage>()

    dispatch_async(...) {
         // do some crazy logic, or go to the internet and get a UIImageView.  Check some Image Caches.
         let i = UIImage()
         p.completeWithSuccess(i)
    }
    return p.future
}

A Promise is a promise to send something back a value (of type T) in the future. When it's ready.. A Promise has to be completed with either Success/Fail or Cancelled. Don't break your promises! Always complete them. And everyone will be happy. Especially your code that is waiting for things.

But it also means the API doesn't really need to bake a whole bunch of custom callback block handlers that return results. And worry about what dispatch_queue those callback handlers have to running in. Do you dispatch to mainQ before you call your callback handlers? Or after? Nobody seems to agree.

But the Future object already offers a lot of cool built ways to get told when data is ready and when it fails. And can handle which GCD queue is required for this reply.

The api just has to emit what he promised. The Future will take care of getting it to the consumer.

And since Futures can be composed from Futures, and Futures can be used to complete Promises, it's easy to integrate a number of complex Async services into a single reliable Future. Mixing things like network calls, NSCache checks, database calls.

It also "inverts" the existing dispatch_async() logic. Where first you call dispatch_async(some_custom_queue) and THEN you call some api call to start it working.

func oldwayToGetStuff(callback:(NSData) -> Void) {
    dispatch_async(StuffMaker().custom_queue_for_stuff)  {

        // do stuff to make your NSData
        let d = StuffMaker().iBuildStuff()

        dispatch_async(dispatch_get_main()) {
            callback(d)
        }
    }
}

notice how I forgot to add error handling in that callback. What if iBuildStuff() times out? do I add more properties to the callback block? add more blocks? Every API wants to do it different and every choice makes my code less and less flexible.

class StuffMaker {
    func iBuildStuffWithFutures() -> Future<NSData> {
        let p = Promise<NSData>()
        dispatch_async(self.mycustomqueue)  {
             // do stuff to make your NSData
            if (SUCCESS) {
                let goodStuff = NSData()
                p.completeWithSuccess(goodStuff)
            }
            else {
                p.completeWithFail(NSError())
            }
        }
        return p.future()
    }
}

Notice we are now calling StuffMaker() directly, without having to dispatch first. And I'm not calling dispatch_async() AGAIN before I call the callback block. I will let the consumer of the Future decide where he wants his handlers to run.

Now you 100% guarantee that the code you want will ALWAYS run in the dispatch_queue you want. It just returns a Future object.

Documentation

FutureKit documentation is being written as Xcode Playgrounds. The best way to start is to open the FutureKit.workspace and then opening the Playground inside. (If you open the Playgrounds outside of the workspace, then FutureKit module may not import correctly). The Xcode Playgrounds probably require Xcode 6.3 (in order to see the Markup correctly)

If you are impatient, or not near your copy of Xcode, you can try to read the first intro "raw" playground here: https://github.com/FutureKit/FutureKit/blob/master/FutureKit-Future.playground/Contents.swift

Help out!

I would love it to get feedback! Tell me what you think is wrong. You can follow @swiftfuturekit to get announcements (when we make them).

futurekit's People

Contributors

andystanton avatar colinta avatar heiberg avatar jrgoodle avatar jstewuk avatar mishagray avatar modocache avatar natashatherobot avatar nolanlawson avatar nrewik avatar ntnhon avatar readmecritic avatar stanfeldman avatar tommybananas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

futurekit's Issues

mapAsOptional() has impossible function signature

In Xcode 9 beta 1, this function no longer compiles:

    public func mapAsOptional<O : OptionalProtocol>() -> Completion<O.Wrapped?> {

        return self.map { v -> O.Wrapped? in
            return v as? O.Wrapped
        }

    }

This is because when calling it there is no way to infer the generic parameter for 'O' (try it in 8.3 -- you can't actually call this function).

Previously we would allow such definitions that cannot be called, but now we reject them. I think you can just remove the function in question, or change it to the following:

    public func mapAsOptional<Wrapped>() -> Completion<Wrapped?> {
      ...
    }

Build error on Xcode 9 Beta 3

I am using Carthage dependency to load FutureKit in our project. However, during build phase it is failing with following error on Xcode 9 Beta 3. (Screenshot attached).

Adding following line in the Error extension seems to be fixing the build error.

var userInfo: [AnyHashable: Any] { return [:] }

Just want to confirm if this is a legit error and then we can put PR to fix it
screen shot 2017-07-27 at 4 52 08 pm

Multiple futures

Can I make Promise/Future of multiple futures, lets say I have 2 API calls one returning some mapped object like Article and the other simple Integer. How do I combine those two to single Future, cause I wanna do something when both of these are done :)

Never-ending process when building or archiving.

Hi

I added FutureKit to my project manually and it works great when i build it and test, but whenever i try to archive and it gets to FutureKit iOS it spins up a swift process taking up 99% CPU and never gets further than in building than "Compiling Swift source files". I also tried just opening the project and running it in order to build the framework and just import that, but the same thing happens. The same thing also happens if i use carthage.

3.0.1 release?

I'd love to have an official release with the app extension API fix, so that I can use this framework in an extension without getting a warning in xcode, and so that I don't have to point to a specific commit in my cartfile. Is this something that can be done relatively soon or are there other issues that need to be resolved before a point release first?

Edit: I'd love for my PR #75 to be pulled in at the same time, so that swiftpm can easily build futurekit :)

Combining multiple requests

I am looking for a way where FutureKit would allow combining multiple requests. For example, I have requests, request1 and request2. I want to fire them simultaneously and wait until both requests return the result. I also want to make sure results are returned in order.

If I fire request1 and request2 and they return data1 and data2 respectively, the API should return data1 and data2 serially in order. I was wondering if this is something possible with current FutureKit implementation.

To give more context this could be more like combineLatest signal from ReactiveCocoa.

Warnings in the new XCode Version 8.3.2

I get 6 warnings in the current version of XCode. Nothing serious as far as I can judge. But it sticks out in otherwise clean code. :o)

Thanks for the great library and kind regards
B

[question] any dedicated way to separate the construction and execution of the promise/future?

In a readme example the work starts right away when the promise and future are created.

class StuffMaker {
    func iBuildStuffWithFutures() -> Future<NSData> {
        let p = Promise<NSData>()

>>>        dispatch_async(self.mycustomqueue)  {
             // do stuff to make your NSData
            if (SUCCESS) {
                let goodStuff = NSData()
                p.completeWithSuccess(goodStuff)
            }
            else {
                p.completeWithFail(NSError())
            }
        }
        return p.future()
    }
}

What do you think about the idea of having some sort of func start() method on the Future class so that the execution could be deffered?

let dataFuture = StuffMaker().iBuildStuffWithFutures()
dataFuture.onSuccess
{
  data in

  // handle result
}

// maybe at some other place after passing it around
dataFuture.start()

As of now, the only way is using the client code to defer the execution manually

class StuffMaker 
{
    let p = Promise<NSData>()

    func iBuildStuffWithFutures() -> Future<NSData> 
   {
         return p.future()
   }

   func startBuildingStuff()
   {
        dispatch_async(self.mycustomqueue)  {
             // do stuff to make your NSData
            if (SUCCESS) {
                let goodStuff = NSData()
                p.completeWithSuccess(goodStuff)
            }
            else {
                p.completeWithFail(NSError())
            }
        }
   }

Swift 3.0 migration

Hi,

Just wanted to ask when/if FutureKit is going to get a syntactic revamp for the new Swift 3.0 Guidelines?

Also, is it regularly maintained?

Thanks!

Error in completeWithSuccess() on Swift 4

If completeWithSuccess() is used on a Promise<Void> under Swift 4, an error is shown

Missing argument for parameter #1 in call

Is there any way to create an extension that will bypass this?
I tried

extension Promise {
    public final func completeWithVoidSuccess() {
        completeWithSuccess(())
    }
}

but it did not work. Tried with completeWithSuccess(Void), but no success too.

The only possible solution I have at the moment is to convert the Promise<Void> to Promise<Bool> and just fulfil it with completeWithSuccess(true).

make return value of onComplete discardable

Hi,

"onSuccess" is non-discardable because most of the time we have to handle "onFail" event. That's great, but I think "onComplete" should be @discardableResult because in most cases, people are gonna handle success, failed and canceled events within one block.

For now, I have to add .ignoreFailure() at the tail which is somewhat redundant. Any good reason that onComplete should not be discardable?

Thanks,
Justin Yan
[email protected]

Crash in Synchronization.swift

Hi,
We're using FutureKit in XCode 9.1 with xcode9 branch (Swift 3.2) in an App for iOS/macOS that handles the processing of many files.
Since we upgraded from XCode 8.3 (Swift 3.1) we observe a strange crash
at runtime in PThreadMutexSynchronization.lockAndModify(waitUntilDone:modifyBlock:then:) [Synchronization.swift].

This only happens sometimes (~ 1:20) and seems like some kind of race condition.
We tried different synchronization flags like barrierSerial, serialQueue or NSLock but they all crash somewhere in their corresponding lockAndModify method.

May this be caused by long Future-chains? We saw this crash in Tests where we had ~ 6000 futures chained with onSuccess/onComplete.

As soon as we get a crash again I will attach a Screenshot of the position in Code.

Thanks!

Crash in OSSpinLockSynchronization

This is an unreproducible one-off crash, so I just wanted to leave it here for future reference. It occurred in the wild for a user and was reported via Fabric.io.

From the mangled symbols it looks like it might be the UnSafeMutableContainer<OSSpinLock> property self.lock inside OSSpinLockSynchronization which is causing this issue.

The application was calling .onSuccess(.UserInteractive) on a Future from the main thread.
Device: non-jailbroken iPhone running iOS 9
FutureKit version: 1.2.0

This is the top of the call stack. The rest is application code + system libraries.

EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x50000000139032db
Thread : Crashed: com.apple.main-thread
0  FutureKit                      0x1009c6d40 _TFC9FutureKit25OSSpinLockSynchronization12synchronizedurfS0_FFT_q_q_ + 80
1  FutureKit                      0x1009c6e58 _TFC9FutureKit25OSSpinLockSynchronization13lockAndModifyurfS0_FT13waitUntilDoneSb11modifyBlockFT_q_4thenGSqFq_T___T_ + 128
2  FutureKit                      0x1009c7110 _TFC9FutureKit25OSSpinLockSynchronization18lockAndModifyAsyncurfS0_FTFT_q_4thenFq_T__T_ + 144
3  FutureKit                      0x1009c7b98 _TTWC9FutureKit25OSSpinLockSynchronizationS_23SynchronizationProtocolS_FS1_18lockAndModifyAsyncu__Rq_S1__fq_FTFT_qd__4thenFqd__T__T_ + 88
4  FutureKit                      0x10098511c _TFC9FutureKit6Future10onCompleteu__rfGS0_q__FTOS_8Executor5blockFzT6resultGOS_12FutureResultq___GOS_10Completionqd____GS0_qd___ + 568
5  FutureKit                      0x100985f24 _TFC9FutureKit6Future9onSuccessu__rfGS0_q__FTOS_8Executor5blockFzq_GOS_10Completionqd____GS0_qd___ + 200
6  FutureKit                      0x100987400 _TFC9FutureKit6Future9onSuccessu__rfGS0_q__FTOS_8Executor5blockFzq_GS0_qd____GS0_qd___ + 200

Allow futurekit to build via carthage with Xcode 9

Currently when I try to build FutureKit 3.0.0 with carthage and Xcode 9, I get build errors (see this gist for the build output). We want to experiment with xcode 9 but can't until this is resolved. Is this just a project settings tweak or is there something more fundamental that the Xcode 9 compiler in swift 3 mode expects that futurekit isn't doing?

Cancellation deadlocks

I'm seeing a pattern of deadlocks when attempting to cancel futures via a cancellation token that I can't make sense of.

I managed to boil it down to a pretty simple reproduction. Maybe I'm doing something wrong here, but I'm not sure what it is.

Let's start out with a utility function creating a simple, cancellable, long-running future:

func createFuture() -> Future<String> {
    let p = Promise<String>()
    p.automaticallyCancelOnRequestCancel()
    Executor.Default.executeAfterDelay(10) {
        p.completeWithSuccess("Done")
    }
    return p.future
}

This future will attempt to complete after 10 seconds.

In the following we'll try to cancel this future after 1 second.

Works fine

let future = createFuture()
let token = future.getCancelToken()
Executor.Default.executeAfterDelay(1) {
    token.cancel()
}

This works as expected. The future is cancelled after 1 second, and completeWithSuccess has no effect when that block runs after 10 seconds.

Deadlock 1

If we change the executor to .Main then the call to token.cancel() never completes. The main thread is deadlocked.

let future = createFuture()
let token = future.getCancelToken()
Executor.Main.executeAfterDelay(1) {
    token.cancel() // NEVER RETURNS
}

My attempts at troubleshooting:

It seems that token.cancel() goes through the onCancel handler set when the token was issued. This handler calls Future._cancelRequested with a synchronization object. This synchronization object is equal to future.synchObject and was given to the token when it was issued. We lock the object and proceed with the cancellation.

Because we used automaticallyCancelOnRequestCancel the handler attempts to complete the future immediately as part of the cancellation.

It ends up invoking future.completeAndNotify() which then tries to lock future.synchObject again. But we're already inside a lockAndModify on that object from the token.cancel() call, and so we have a deadlock.

Deadlock 2

Now let's go back to the cancellation which worked fine, invoking cancel on the .Default executor.

But now we add an onSuccess handler to the future.

let future = createFuture().onSuccess { _ in print("onSuccess") }
let token = future.getCancelToken()
Executor.Default.executeAfterDelay(1) {
    token.cancel() // NEVER COMPLETES
}

This also triggers a deadlock and token.cancel() never completes.

Workaround

Since it is the immediate completion of the future upon cancellation which causes the deadlock, one way to avoid this issue is to always return .Continue from the onRequestCancel of the promise. From the docs it seems this is recommend for other reasons as well.

I don't understand what makes the first example work, while the last two deadlock.

But it looks like I really should avoid returning .Complete(_) from onRequestCancel, which of course is what automaticallyCancelOnRequestCancel does?

I'm not 100% sure if this is a bug or a user error.

[question] flatmap for futures?

I was playing around with futurekit last week and ran into a weird roadblock, in that I couldn't return a future in an onSuccess block and have that future be the one that is chained on moving forward, making it effectively a flatmap operation. Is this something that was tried and just didn't work, or is this a feature that can be made to work if someone puts the time in? I wouldn't be averse to trying it out if there's no technical or other reason not to.

Thanks!

Third party libraries extensions

I am using some third party libraries in my projects such as Parse and Net.
So I am going to write FutureKit extensions for them.
Should I put these extensions inside FutureKit in some folder or should I create a different repo for them?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.