LoginSignup
0
1

More than 1 year has passed since last update.

ReactiveSwift 主要コンポーネントまとめ

Posted at

この記事について

この記事は今更ですが、ReactiveSwiftの主要コンポーネントについてとても簡単にまとめたメモをQiitaに移植したものです。

ReactiveSwiftを構成する主なコンポーネント

ReactiveSwiftを構成する主なコンポーネントは以下の6つです。

    - Signal
    - SignalProducer
    - Property 
    - MutableProperty
    - バインディング演算子(<~)
    - Action

Signal / SignalProducer

  • Signal

    SignalはEventのストリームを流し続ける(Hot)

    Failed/Completed/Interrupted”のどれかが流れるとストリームを終了する

  • SignalProducer

    SignalProducerは、購読されたらストリームを流す(Cold)

Property / MutableProperty

  • MutableProperty

    ・購読可能な値を保持している

    ・値の変更はもちろんSignal/SignalProducerから購読可能

    ・同期的に値を取得することができる

    let selectedArtist = MutableProperty<[Artist]>([])
    //Signalで購読
    selectedArtist.signal.observeValues { selectedArtist in
    	print(selectedArtist)
    }
    //値の変更と取得は'value'で可能
    selectedArtist.value = [
    	Artist(id: 123456, name: "hoge")
    ]
    
  • Property

    読み取り専用 ←これがMutablePropertyとの違い

    ・MutablePropertyとインターフェースはほぼ同じ

    ・外部に公開するときに便利

let mutableState = MutableProperty(State.notLoaded)
//↓これはMutablePropertyなので値の更新ができる
mutable.value = .loading
//↓MutablePropertyをPropertyに変換
let state = Property(caputuring: mutableState)
//↓これはPropertyなので値の更新はできないため、コンパイルエラー
state.value = .notLoaded ←これはエラー

まとめると

・Propertyは読み取り専用

・MutablePropertyは読み書き可能

・それ以外のできることはほぼ同じ

Property / MutableProperty比較表

Property MutablePropety
読み取り
書き込み ×
map後の型 Property Property

Tips💡 - Propertyのmapが便利

例 : Usernameが5文字以上の時に登録ボタンがアクティブになる画面

struct ViewModel {
	let username: MutableProperty<String>
	let isEnabled: Property<Bool>

	init() {
		self.username = MutableProperty("")
		self.isEnabled = userName.map { userName in
			userName.count >= 5
		}
	}
}

バインディング演算子( <~ )

  • 値のバインディングに使用する

例:↑Tipsの続き

viewModel.userName <~ textField.reactive.continuousTextValues.map { $o ?? "" }
registerButton.reactive.isEnabled <~ viewModel.isEnabled

💡Points

・左辺にバインドされる側を描く(MutableProperty)

・右辺に値を送る側を置く(Signal/SignalProducer、Property/MutableProperty)

・右辺がProperty/MutablePropertyの場合は現在の値が流れてくる

・disposeは省略が可能

Action

  • Input を与えてOutputもしくはErrorを流す

まとめ

今回は簡易的にまとめたものなのでとてもざっくりですが、以下の記事がとてもわかりやすいです。
ほとんど記事のスライドに沿った簡易まとめになっています。

参考文献

「入門 ReactiveSwift 」という発表をした
https://blog-rookery.com/posts/introduction-to-reactive-swift/
ReactiveSwiftを克服する Part1 〜 Part5
https://qiita.com/taka1068/items/5d916f1e68cbcdce0121

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1