LoginSignup
6
7

More than 5 years have passed since last update.

Bond

Posted at

abstract

  • bondは循環参照を防いでいる
  • プロパティのvalueが変化したら自動でbindしたもののvalueも変化するという挙動をさらっと書けるのが重要なポイント

TableViewのCell描画を例にすると、、、、
bondは、宣言的な手続き(arrayが更新したらtableviewを描画し直してくれるメソッドが中にある)
<=>命令的な手続き(関数の中に関数を呼ぶ命令が書いている)

Bond-Demo-Appも良い

Bond README.mdまとめ

Bond is a Swift binding framework that takes binding concept to a whole new level. It's simple, powerful, type-safe and multi-paradigm - just like Swift.

Bond was created with two goals in mind: simple to use and simple to understand. One might argue whether the former implies the latter, but Bond will save you some thinking because both are true in this case. Its foundation are few simple classes - everything else are extensions and syntactic sugars.

Note: This document describes Bond v4. If you are using a previous version of the framework, check out the Migration to Bond v4 section. Bond v4 is the only officially supported version for Swift 2.0.

cf)
syntax sugar(糖衣構文):初心者でもわかるように作られた、本来の構文の様式美を破壊するような簡素な構文

  • map
textField.bnd_text
  .observe { text in
    print(text)
  }
textField.bnd_text
  .map { "Hi " + $0 } // $0はtextFieldに書き込まれたvalue
  .bindTo(label.bnd_text)
  • filter, TouchUpInside
button.bnd_controlEvent
  .filter { $0 == UIControlEvents.TouchUpInside }
  .observe { e in
    print("Button tapped.")
  }
button.bnd_tap
  .observe {
    print("Button tapped.")
  }  
  • 複数の引数から一つの返り値も出せる
combineLatest(emailField.bnd_text, passField.bnd_text)
  .map { email, pass in
    return email.length > 0 && pass.length > 0
  }
  .bindTo(button.bnd_enabled)


Bond's power is not, however, in coupling various UI components, but in the binding of a Model (or a ViewModel) to a View and vice-versa. It's great for MVVM paradigm. Here is how one could bind user's number of followers property of the model to the label.

Point here is not in the simplicity of value assignment to text property of a label, but in the creation of a binding which automatically updates label text property whenever number of followers change.

viewModel.numberOfFollowers
  .map { "\($0)" }
  .bindTo(label.bnd_text)
viewModel.username.bidirectionalBindTo(usernameTextField.bnd_text)

=>numberOfFollowersのvalueが変化したらその値が自動的にlabelに反映されるのが重要なポイント

Say you have an array of repositories you would like to display in a collection view. For each repository you have a name and its owner's profile photo. Of course, photo is not immediately available as it has to be downloaded, but once you get it, you want it to appear in collection view's cell. Additionally, when user does 'pull down to refresh' and your array gets new repositories, you want those in collection view too.
instead of implementing a data source object, observing photo downloads with KVO and manually updating the collection view with new items, with Bond you can do all that in just few lines:

repositories.bindTo(collectionView) { indexPath, array, collectionView in
  let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! RepositoryCell
  let repository = array[indexPath.section][indexPath.item]

  repository.name
    .bindTo(cell.nameLabel.bnd_text)
    .disposeIn(cell.onReuseBag)

  repository.photo
    .bindTo(cell.avatarImageView.bnd_image)
    .disposeIn(cell.onReuseBag)

  return cell
})

参考:KVOの意味はKey-Value Observingの略で、プロパティーの値の変化を通知してくれる仕組み。SwiftでKVOを試してみる

The Event Producer

At the core of the framework is the class "EventProducer".
It represents an abstract event generator that provides the mechanisms that enable interested parties, called observers, to observe generated events. For example, it can be used to represent a subject with a mutable state, like a variable or an array, and then inform observers of the state change whenever it happens. On the other hand it can represent an action, something without a state, and generate an event whenever the action occurs.

The Observable

The most common use of the event producer is through its subclass "Observable" that can mimic a variable or a property and enable observation of its change. The Observable is a generic type generalized over the wrapped value type. As the EventProducer is also a generic type, generalized over its event type, it is only natural to specialize such event producer to the type of the values it can encapsulate. To create the observable just initialize it with a value:

参考:generic typeについては次の記事によくまとめられています
Swift ジェネリックス(Generics)

let captain = Observable(“Jim”)

Swift automatically infers the type of the observable from the passed value. In our example the type of the variable captain is Observable. To change its value afterwards, you can use the method next:

nextメソッドにより、valueをセットでき、valueメソッドでvalueを取得できる。
captain.next(“Spock”)

print(captain.value) // prints: Spock

Now comes the interesting part. In order to make the observable useful it should be observed. Observing the observable means observing the events it generates, that is, in our case, the values that are being set. To observe the observable we register a closure of the type "EventType -> ()" to it with the method observe, where EventType is the event (value) type:

captain.observe { name in
  print(“Now the captain is \(name).”)
}

// prints: Now the captain is Spock.

Now, whenever the value is changed, the observer closure will be called and side effects performed:

captain.next(“Scotty” ) // prints: Now the captain is Scotty.

bindToは二次元配列じゃないと使えない(FaceBook参照)

ここまでは読んだ。


propagate: 繁殖する
prepend: 先頭に挿入する、
observable: 観察すべき、注目すべき
snippet: 断片
asynchronous: 非同時性の
mutable: 変わりやすい


参考

recruit tech blog

関数型リアクティブプログラミングをするためのオープンソース

キーワード
・Generics
...The Swift Programming Language; Generics
...ジェネリクス|Swift言語を学ぶ
・type constraint syntax(型制約)
・associated types(関連型)


お手製Swift Bondでリアクティブプログラミング

キーワード

  • RFP
  • 途中なので残りを読んでキーワードを埋める

Solving the binding problem with Swift

これもまだ読んでないので読んで埋める

c
objectがなくなったらbindも勝手にunbindされるが、cellは再利用されるので勝手にunbindされない
-->prepareforreuseというメソッドがcellにはある
メソッド内部で、onReuseBagにbindの情報を入れておく
->scrollしてcellが再利用される前にprepareforReuseがcallされる
->onReuseBagに入っていたbindはunbindされる
->新たにbindすることが可能

bondではdisposeInすることで再利用する前にunbindをしている????

6
7
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
6
7