An actor model library for swift.

Related tags

Concurrency Aojet
Overview

Aojet

GitHub license GitHub release Carthage compatible

Aojet is an actor model implemetion for swift.

Features

  • Asynchronous, non-blocking and highly performant message-driven programming model
  • Safe as well as efficient messaging
  • Message ordering using Local Synchronization Constraints
  • Fair scheduling
  • Modular and extensible
  • A promise implementation for general usage
  • Portable(Support iOS and Mac platform currently)

Requirements

  • Swift 3.0
  • iOS 8.0+ or macOS 10.10+

Installation

Aojet is available through Carthage. Add this line to your Cartfile

github "aojet/Aojet"

Usage

Make an Actor

This is a simple actor implementation:

class SomeActor: Actor {
  override func onReceive(message: Any) throws {
    switch message {
    case let m as DoSomething:
      doSomething(object: m.object)
    default:
      try super.onReceive(message: message)
    }
  }

  func doSomething(object: Any) { //This should run on the actor thread.
    print(Thread.current)
    print("Do something with object: \(object)")
    //Do something
  }

  struct DoSomething {
    let object: Any
  }

}

Create ActorRef

let actorSystem = ActorSystem.system
actorSystem.traceInterface = ActorTrace() //For internal logging
let actor = try actorSystem.actorOf(path: "testActor", creator: AnyActorCreator{ () -> Actor in
  return SomeActor()
})

Send Message to ActorRef

actor.send(message: SomeActor.DoSomething(object: "An object")) //Success
actor.send(message: "An string") //Drop
actor.send(message: SomeActor.DoSomething(object: "Another object")) //Success

Make an AskableActor

class SomeActor: AskableActor {

  override func onAsk(message: Any) throws -> Promise<Any>? {
    switch message {
    case let m as AskSomething:
      return askSomething(object: m.object)
    default:
      let p = try super.onAsk(message: message)
      print("Promise: \(p)")
      return p
    }
  }

  override func onReceive(message: Any) throws {
    switch message {
    case let m as DoSomething:
      doSomething(object: m.object)
    default:
      try super.onReceive(message: message)
    }
  }

  func doSomething(object: Any) { //This should run on the actor thread.
    print(Thread.current)
    print("Do something with object: \(object)")
    //Do something
  }

  func askSomething(object: Any) -> Promise<Any> { //This should run on the actor thread.
    print(Thread.current)
    print("Ask something with object: \(object)")

    return Promise(value: "A response")
  }

  struct DoSomething {
    let object: Any
  }
  
  struct AskSomething {
    let object: Any
  }
}

Make an Ask Request

 let p1: Promise<String> = actor.ask(message: SomeActor.AskSomething(object: "An object for ask"))
 p1.then { (res) in
   print("Ask response:\(res)")
 }.failure { (error) in
   print("Ask error:\(error)")
 }
  

Promise Usage

There are some ways to create a promise:

//Define an error for test
enum TestError: Error {
  case general(message: String)
}

//Immediate Promise
let p1 = Promise(value: 1)
let p2 = Promise<Int>(error: TestError.general(message: "Test error."))

//Async Promise
let p3 = Promise<String> { (resolver) in
  let url = URL(string: "https://api.ipify.org")
  let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
    if error != nil {
      resolver.error(error!)
    } else if data != nil {
      let s = String(bytes: data!, encoding: String.Encoding.utf8)
      print(s)
      resolver.result(s)
    } else {
      resolver.result(nil)
    }
  }
  task.resume()
}
You might also like...
GroupWork is an easy to use Swift framework that helps you orchestrate your concurrent, asynchronous functions in a clean and organized way
GroupWork is an easy to use Swift framework that helps you orchestrate your concurrent, asynchronous functions in a clean and organized way

GroupWork is an easy to use Swift framework that helps you orchestrate your concurrent, asynchronous functions in a clean and organized way. This help

SwiftCoroutine - Swift coroutines for iOS, macOS and Linux.
SwiftCoroutine - Swift coroutines for iOS, macOS and Linux.

Many languages, such as Kotlin, Go, JavaScript, Python, Rust, C#, C++ and others, already have coroutines support that makes the async/await pattern i

Venice - Coroutines, structured concurrency and CSP for Swift on macOS and Linux.
Venice - Coroutines, structured concurrency and CSP for Swift on macOS and Linux.

Venice provides structured concurrency and CSP for Swift. Features Coroutines Coroutine cancelation Coroutine groups Channels Receive-only chan

Syntactic sugar in Swift for asynchronous dispatches in Grand Central Dispatch

Async Now more than syntactic sugar for asynchronous dispatches in Grand Central Dispatch (GCD) in Swift Async sugar looks like this: Async.userInitia

Elegant ⏱ interface for Swift apps

Each Elegant ⏱ interface for Swift apps Each is a NSTimer bridge library written in Swift. Features Requirements Installation Usage Leaks License Feat

 GCDTimer - Well tested Grand Central Dispatch (GCD) Timer in Swift
GCDTimer - Well tested Grand Central Dispatch (GCD) Timer in Swift

GCDTimer Well tested Grand Central Dispatch (GCD) Timer in Swift. Checkout the test file. Usage Long running timer import GCDTimer

Schedule timing task in Swift using a fluent API. (A friendly alternative to Timer)
Schedule timing task in Swift using a fluent API. (A friendly alternative to Timer)

Schedule(简体中文) Schedule is a timing tasks scheduler written in Swift. It allows you run timing tasks with elegant and intuitive syntax. Features Elega

Grand Central Dispatch simplified with swift.

GCDKit GCDKit is Grand Central Dispatch simplified with Swift. for Swift 1.2: Use version 1.0.1 for Swift 2.1 / 2.2: Use the master branch Introductio

Queues, timers, and task groups in Swift
Queues, timers, and task groups in Swift

Dispatcher eases the pain of using Grand Central Dispatch by introducing 4 new Swift classes. Dispatcher Queue Group Timer Requirements Swift 2.0+ Ins

Comments
  • Manual Installation

    Manual Installation

    CocoaPods and Carthage are awesome tools and make our life really easier, but there are some devs who still don't know how to use them.

    It would be cool to add the Manual installation guide in your README.md. You can take a look at my iOS Readme Template to see how you can do it.

    enhancement 
    opened by lfarah 0
Owner
null
**`withCheckedContinuation`'s body will run on background thread in case of starting from main-actor.**

ConcurrencyContinuationReproduce Differences of Concurrency behaviors between Xcode 14.0 and 14.1 Xcode 14.0 iOS 13+: Runs on main (inherited same con

Hiroshi Kimura 4 Dec 20, 2022
Hydra ⚡️ Lightweight full-featured Promises, Async & Await Library in Swift

Lightweight full-featured Promises, Async & Await Library in Swift What's this? Hydra is full-featured lightweight library which allows you to write b

Daniele Margutti 2k Dec 24, 2022
Kommander is a Swift library to manage the task execution in different threads.

A lightweight, pure-Swift library for manage the task execution in different threads. Through the definition a simple but powerful concept, Kommand.

Intelygenz 173 Apr 11, 2022
AwaitKit is a powerful Swift library which provides a powerful way to write asynchronous code in a sequential manner.

AwaitKit is a powerful Swift library inspired by the Async/Await specification in ES8 (ECMAScript 2017) which provides a powerful way to write asynchronous code in a sequential manner.

Yannick Loriot 752 Dec 5, 2022
AutoLogout is a swift library for managing user's session on inactivity.

On user inactivity, it will show an alert box to continue session or Logout as shown in screen shot, according to time set.

Adnan Yousaf 9 Jul 7, 2022
Hydra: Lightweight full-featured Promises, Async-Await Library in Swift

Async Functions for ECMAScript The introduction of Promises and Generators in EC

Ecma TC39 1.6k Oct 17, 2022
A declarative state management and dependency injection library for SwiftUI x Concurrency

A declarative state management and dependency injection library for SwiftUI x Concurrency

Ryo Aoyama 199 Jan 1, 2023
Lightweight async/await networking library with interceptor support - usable from iOS 13+.

Lightweight async/await networking library with interceptor support. ?? Getting started AsyncNetwork's session acts as a wrapper to URLSession by addi

Paul 9 Oct 4, 2022
A complete set of primitives for concurrency and reactive programming on Swift

A complete set of primitives for concurrency and reactive programming on Swift 1.4.0 is the latest and greatest, but only for Swift 4.2 and 5.0 use 1.

AsyncNinja 156 Aug 31, 2022
Futures is a cross-platform framework for simplifying asynchronous programming, written in Swift.

Futures Futures is a cross-platform framework for simplifying asynchronous programming, written in Swift. It's lightweight, fast, and easy to understa

David Ask 60 Aug 11, 2022