Code Monkey home page Code Monkey logo

promisify's Introduction

promisify - Convert callback functions to Future

This μFramework introduces a way to convert old callback-based functions that accept callback as an argument, to functions that return Future<T, Error> instances. It allows painless chaining for function calls, instead of pyramid of callback doom.

Usage

Lets put that you are migrating your app to Combine framework and you have to use some of your code that may look like that little service below.

class UserNotificationService {
  
  static let shared = UserNotificationService()
  private init() {}
  
  func authorizeNotifications(granted: @escaping (Bool) -> Void) {
    UNUserNotificationCenter
      .current()
      .requestAuthorization(
        options: [.alert, .sound, .badge]
      ) { (permissionGranted, error) in
        let value = permissionGranted && error == nil
        granted(value)
      }
  }
  
  func getAuthorizationStatus(granted: @escaping (Bool) -> Void) {
    UNUserNotificationCenter
      .current()
      .getNotificationSettings { (settings) in
        let value = settings.authorizationStatus == .authorized
        granted(value)
      }
  }
}

Using this code above as-is will be clumsy, requiring you to manually create wrappers each time you want to use it. Like this:

// for simplicity details are omitted

turnOnNotificationsButtonTap
    .flatMap { _ -> AnyPublisher<Bool, Never> in
        return Future { promise in
            UserNotificationService.shared().authorizeNotifications { granted in
                promise(.success(granted))
            }
        }
        .eraseToAnyPublisher()
    }
    .sink(receiveValue: { value in 
        print("Notifications are allowed - \(value)")
    })

Instead, with promisify you can write code like this:

turnOnNotificationsButtonTap
    .flatMap { _ -> AnyPublisher<Bool, Never> in
        return promisify(UserNotificationService.shared().authorizeNotifications)().eraseToAnyPublisher() // eloquent and simple
    }
    .sink(receiveValue: { value in 
        print("Notifications are allowed - \(value)")
    })

If your callback-based functions take arguments, just add them after promisify call:

// example
func iTakeArguments(arg0: String, arg1: String, completion: () -> Void) {
    
}

// usage

let result: Promise<Void, Never> = promisify(iTakeArguments)(("argument0", "argument1"))

Installation

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler. It is in early development, but Alamofire does support its use on supported platforms.

Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/alexey-savchenko/promisify.git", .branch("main"))
]

promisify's People

Watchers

James Cloos avatar Alexey Savchenko avatar

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.