var rac3 = reactivecocoa + swift

37
var RAC3 = Reac,veCocoa + Swi2 @ikesyo #rac_kansai Reac%veCocoa勉強会関西 2014.07.26 Sat @はてな京都オフィス

Upload: syo-ikeda

Post on 18-Jun-2015

5.007 views

Category:

Engineering


4 download

DESCRIPTION

2014-07-26(土)に開催された「ReactiveCocoa勉強会関西【Cocoa勉強会関西特別編】」の発表資料です。 https://atnd.org/events/53540

TRANSCRIPT

Page 1: var RAC3 = ReactiveCocoa + Swift

var$RAC3$=$Reac,veCocoa$+$Swi2@ikesyo#rac_kansai

Reac%veCocoa勉強会関西)2014.07.26)Sat)@はてな京都オフィス

Page 2: var RAC3 = ReactiveCocoa + Swift

@ikesyo

いけしょー/池田翔

京都でフリーランスのiOS/Androidエンジニアしています

甘いもの大好き!!お仕事待ってます!

Page 3: var RAC3 = ReactiveCocoa + Swift

Reac%veCocoaのコミッター(Contributor)やってます

Page 4: var RAC3 = ReactiveCocoa + Swift

今日はSwi$ベースになったReac%veCocoa)3.0のご紹介

Page 5: var RAC3 = ReactiveCocoa + Swift

※!注意2014%07%25,)Xcode)6)beta)4時点の内容に基づきます

APIやクラス名など今後変更される可能性は大いにあります

Page 6: var RAC3 = ReactiveCocoa + Swift

RAC$3.0

Page 7: var RAC3 = ReactiveCocoa + Swift

元々はこれh"ps://github.com/Reac3veCocoa/

Reac3veCocoa/pull/966

Page 8: var RAC3 = ReactiveCocoa + Swift
Page 9: var RAC3 = ReactiveCocoa + Swift

_人人人人人人人_> 突然のSwi$ <‾Y^Y^Y^Y^Y^Y‾

Page 10: var RAC3 = ReactiveCocoa + Swift

だけではなく

RACDC%2014:%June%3rd@Github• The$Future$Of$Reac.veCocoa$by$Jus.n$Spahr9Summers$•$GitHub$Reac.ve$Cocoa$Developer$Conference

• h#p://vimeo.com/98100163

• h#ps://github.com/jspahrsummers/the<future<of<reac>vecocoa

Page 11: var RAC3 = ReactiveCocoa + Swift

h"ps://github.com/jspahrsummers/RxSwi8を経て

Page 12: var RAC3 = ReactiveCocoa + Swift

The$Great$Swi,ening$(a.k.a.$the$new$3.0)

h"ps://github.com/Reac3veCocoa/Reac3veCocoa/pull/1382

Page 13: var RAC3 = ReactiveCocoa + Swift

New$Concepts• Generics)Support

• Producer

• Consumer

• Signal

• SignalingProperty

• Promise

• Action

Page 14: var RAC3 = ReactiveCocoa + Swift

Generics(Support型パラメータは当然サポートpublic struct Producer<T> {}public final class Consumer<T>: Sink {}extension NSNotificationCenter { public func rac_notifications (name: String? = nil, object: AnyObject? = nil) -> Signal<NSNotification?>}extension NSURLSession { public func rac_dataProducerWithRequest (request: NSURLRequest) -> Producer<(NSData, NSURLResponse)>}

Page 15: var RAC3 = ReactiveCocoa + Swift

Producer• Cold&RACSignal:&Event&Stream

• Consumerをアタッチしてイベントをproduceする

• Consumer毎に受け取るイベントやタイミングは異なる

• ConsumerがDisposableを持っていて、Producer生成時のクロージャではDisposableを返さない

• consumer.disposable.addDisposable(...)

Page 16: var RAC3 = ReactiveCocoa + Swift

Producer.swi,

public struct Producer<T> { public init(produce: Consumer<T> -> ()) // +[RACSignal createSignal:]

public static func empty() -> Producer<T> // +[RACSignal empty] public static func single(value: T) -> Producer<T> // +[RACSignal return:] public static func error(error: NSError) -> Producer<T> // +[RACSignal error:] public static func never() -> Producer<T> // +[RACSignal never]

// -[RACSignal subscribe:] public func produce(consumer: Consumer<T>) -> Disposable public func produce(consumer: Event<T> -> ()) -> Disposable // -[RACSignal subscribeNext:error:completed:] public func produce( next: T -> (), error: NSError -> (), completed: () -> () ) -> Disposable}

Page 17: var RAC3 = ReactiveCocoa + Swift

Producerの生成例extension RACSignal { public func asProducer() -> Producer<AnyObject?> { return Producer { consumer in let next = { (obj: AnyObject?) -> () in consumer.put(.Next(Box(obj))) }

let error = { (maybeError: NSError?) -> () in let nsError = maybeError.orDefault(RACError.Empty.error) consumer.put(.Error(nsError)) }

let completed = { consumer.put(.Completed) }

let disposable: RACDisposable? = self.subscribeNext(next, error: error, completed: completed) consumer.disposable.addDisposable(disposable) } }}

Page 18: var RAC3 = ReactiveCocoa + Swift

Consumer• like:'id<RACSubscriber> subscriber

• SinkプロトコルのputにEvent<T>でラップした値を渡す

• public func put(event: Event<T>) {}

• 従来の'-sendNext:'などの代わり

• Producerのproduceメソッドに'Event<T> -> ()'のクロージャをConsumerとして渡せる

Page 19: var RAC3 = ReactiveCocoa + Swift

Consumer.swi,

public final class Consumer<T>: Sink { public typealias Element = Event<T>

public let disposable = CompositeDisposable()

public init<S: Sink where S.Element == Event<T>>(_ sink: S) public convenience init(put: Event<T> -> ()) public convenience init( next: T -> () = emptyNext, error: NSError -> () = emptyError, completed: () -> () = emptyCompleted)

public func put(event: Event<T>)}

Page 20: var RAC3 = ReactiveCocoa + Swift

Consumerの使用例extension Producer { public func asDeferredRACSignal<U: AnyObject>(evidence: Producer<T> -> Producer<U?>) -> RACSignal { return RACSignal.createSignal { subscriber in let selfDisposable = evidence(self).produce { event in switch event { case let .Next(obj): subscriber.sendNext(obj)

case let .Error(error): subscriber.sendError(error)

case let .Completed: subscriber.sendCompleted() } }

return RACDisposable { selfDisposable.dispose() } } }}

Page 21: var RAC3 = ReactiveCocoa + Swift

補足1• evidenceという型チェックにより、特定の型パラメータを持つProducerでのみメソッドを呼べるように制限

• Objec've)CとのブリッジなのでStructやEnumは渡せず、AnyObjectでクラスオブジェクトだけに制限

• 使い方:,引数に,identityという関数を渡すだけ

Page 22: var RAC3 = ReactiveCocoa + Swift

Iden%ty.swi,/// The identity function, which returns its argument.////// This can be used to prove to the typechecker that a given type A is/// equivalent to a given type B.////// For example, the following global function is normally impossible to bring/// into the `Signal<T>` class:////// func merge<U>(signal: Signal<Signal<U>>) -> Signal<U>////// However, you can work around this restriction using an instance method with/// an “evidence” parameter:////// func merge<U>(evidence: Signal<T> -> Signal<Signal<U>>) -> Signal<U>////// Which would then be invoked with the identity function, like this:////// signal.merge(identity)////// This will verify that `signal`, which is nominally `Signal<T>`, is logically/// equivalent to `Signal<Signal<U>>`. If that's not actually the case, a type/// error will result.public func identity<T>(id: T) -> T { return id}

Page 23: var RAC3 = ReactiveCocoa + Swift

補足2• 例えばScalaではGeneralized-Type-Constraintsという言語機能で同様の制限が可能

• h6p://yuroyoro.hatenablog.com/entry/20100914/1284471301

• h6p://www.ne.jp/asahi/hishidama/home/tech/scala/generics.html#hgeneralizedtype_constraints

Page 24: var RAC3 = ReactiveCocoa + Swift

Signal• Hot%RACSignal:%Behaviour%in%other%FRP

• CompletedやErrorによる終了はなく、常に現在の値を持つ

• T -> ()%のクロージャがオブサーバー%SinkOf<T>%となってobserveする

• ProducerのConsumerと異なり、全てのオブザーバーが同じイベントを同じタイミングで受け取る

• observeを開始した時点で現在値が通知される

Page 25: var RAC3 = ReactiveCocoa + Swift

Signal.swi*

public final class Signal<T> { public var current: T

public init(initialValue: T, generator: SinkOf<T> -> ()) public class func constant(value: T) -> Signal<T>

public func observe<S: Sink where S.Element == T> (observer: S) -> Disposable public func observe(observer: T -> ()) -> Disposable}

Page 26: var RAC3 = ReactiveCocoa + Swift

Signalの生成例extension NSNotificationCenter { public func rac_notifications (name: String? = nil, object: AnyObject? = nil) -> Signal<NSNotification?> { let disposable = ScopedDisposable(SerialDisposable())

return Signal(initialValue: nil) { sink in let observer = self.addObserverForName(name, object: object, queue: nil) { notification in sink.put(notification) }

disposable.innerDisposable.innerDisposable = ActionDisposable { self.removeObserver(observer) }

return () } }}

Page 27: var RAC3 = ReactiveCocoa + Swift

Signal/Observer(SinkOf<T>)の使用例extension Signal { /// Creates a "hot" RACSignal that will forward values from the receiver. /// /// evidence - Used to prove to the typechecker that the receiver is /// a signal of objects. Simply pass in the `identity` function. /// /// Returns an infinite signal that will send the observable's current /// value, then all changes thereafter. The signal will never complete or /// error, so it must be disposed manually. public func asInfiniteRACSignal<U: AnyObject>(evidence: Signal<T> -> Signal<U?>) -> RACSignal { return RACSignal.createSignal { subscriber in evidence(self).observe { value in subscriber.sendNext(value) }

return nil } }}

Page 28: var RAC3 = ReactiveCocoa + Swift

SignalingProperty• 値の変更をSignalとして通知することができるプロパティ用オブジェクト

• KVOの代替手段:&Swi*のクラスにはKVOがなく、監視される側が自分から通知できるように公開する

• func __conversion()&によりラップされた値を透過的に使用することができる

Page 29: var RAC3 = ReactiveCocoa + Swift

SignalingProperty.swi1

public final class SignalingProperty<T>: Sink { public typealias Element = T

public let signal: Signal<T> // setするとsignalのオブザーバーに通知される public var value: T

public init(_ defaultValue: T)

public func __conversion() -> T public func __conversion() -> Signal<T> public func put(value: T)}

Page 30: var RAC3 = ReactiveCocoa + Swift

SignalingPropertyの使用例public class Hoge { var name: SignalingProperty<String> = SignalingProperty("")}

public func printName(name: String) { println(name)}

let hoge = Hoge()

// Stringが必要なのでSignalingProperty<String>から現在の値が取り出されるprintName(hoge.name)

hoge.name.signal.observe { name in println("\(name): name was changed!")}

hoge.name.put("ikesyo")

Page 31: var RAC3 = ReactiveCocoa + Swift

Promise• 単一の値を生成(resolve)する遅延タスクを表現する

• ProducerのようなEvent-Streamではないので複数の値を通知したりはしない

• 値は-public let signal: Signal<T?>-でSignalとして参照できる

• resolve前:-nil,-resolve後:-生成された値-を通知

Page 32: var RAC3 = ReactiveCocoa + Swift

Promise.swi*

public final class Promise<T> { public let signal: Signal<T?>

// 生成時のクロージャの引数の`sink`に`put`することでresolveされる。 // 二度目以降の`put`は無視される。 public init(action: SinkOf<T> -> ())

public func start() -> Promise<T> public func await() -> T

// Promiseのチェーン public func then<U>(action: T -> Promise<U>) -> Promise<U>}

Page 33: var RAC3 = ReactiveCocoa + Swift

Promiseの使用例

public final class Signal<T> { public func firstPassingTest(pred: T -> Bool) -> Promise<T> { return Promise { sink in self.take(1).observe { value in if pred(value) { sink.put(value) } }

return () } }}

Page 34: var RAC3 = ReactiveCocoa + Swift

Ac#on• RACCommandの置き換え

• インプットからアウトプットを返すアクション(主にUI用:&デフォルトでメインスレッドで動作)の実行・結果を提供する

• 個別のアクション実行の結果はPromise<Result<T>で返す

• 結果のチェックはSignal<Result<T>?>なのでobserveで

• 実行結果の値があるのでアクションの合成(チェーン)が可能

Page 35: var RAC3 = ReactiveCocoa + Swift

Ac#on.swi*

public final class Action<Input, Output> { public typealias ExecutionSignal = Signal<Result<Output>?> // RACCommand.executionSignalsと同様 public let executions: Signal<ExecutionSignal?> public var results: Signal<Result<Output>?> // 実行結果 public var executing: Signal<Bool> // 実行中かどうか public let enabled: Signal<Bool> // 有効かどうか public var values: Signal<Output?> // 成功結果 public var errors: Signal<NSError?> // 失敗結果 // アクションとなるクロージャを渡す public init(enabledIf: Signal<Bool>, scheduler: Scheduler = MainScheduler(), execute: Input -> Promise<Result<Output>>) public func execute(input: Input) -> ExecutionSignal // アクションの実行 public func then<NewOutput> // アクションの合成 (action: Action<Output, NewOutput>) -> Action<Input, NewOutput>}

Page 36: var RAC3 = ReactiveCocoa + Swift

Q&A?

Page 37: var RAC3 = ReactiveCocoa + Swift

ありがとうございました!