2017-01-13 4 views
0

私は質問があります:どのように適切にRxDataSourcesでのRx-な方法でこのようなシナリオを実装する:RxSwiftとUICollectionView、のUITableView

我々はUICollectionViewを持つクラス持っている(またはのUITableViewを、私の場合には、それはコレクションビューですが)、結果はすぐには現れず、しばらくしてから非同期的に発生します。

は、私がここにチュートリアルに従ってセクションで私のモデルを実装している: https://github.com/RxSwiftCommunity/RxDataSources

しかし、データは一度しかありjustで作成されます場合には何をすべきか

let sections = [ 
    SectionOfCustomData(header: "First section", items: [CustomData(anInt: 0, aString: "zero", aCGPoint: CGPoint.zero), CustomData(anInt: 1, aString: "one", aCGPoint: CGPoint(x: 1, y: 1)) ]), 
    SectionOfCustomData(header: "Second section", items: [CustomData(anInt: 2, aString: "two", aCGPoint: CGPoint(x: 2, y: 2)), CustomData(anInt: 3, aString: "three", aCGPoint: CGPoint(x: 3, y: 3)) ]) 
] 

Observable.just(sections) 
    .bindTo(collectionView.rx.items(dataSource: dataSource)) 
    .addDisposableTo(disposeBag) 

は私のアイテムが用意されていしばらくしてからコレクションビューを自動的に更新したいのですか?

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

答えて

6

あなたはこのようVariable<[Section]>を使用することができます。

enum Api { 
    /// Network response 
    static func call() -> Observable<[CustomData]> { 
     return .just([CustomData(anInt: 0)]) 
    } 
} 

struct CustomData { 
    let anInt: Int 
} 

class ViewController: UIViewController { 

    @IBOutlet weak var tableView: UITableView! 

    typealias Section = SectionModel<String, CustomData> 
    private let sections = Variable<[Section]>([]) 
    private let dataSource = RxTableViewSectionedReloadDataSource<Section>() 
    let disposeBag = DisposeBag() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // change sections by api call 
     Api.call() 
      .map { (customDatas) -> [Section] in 
       [Section(model: "First section", items: customDatas)] 
      }.bindTo(sections) 
      .addDisposableTo(disposeBag) 

     sections.asDriver() 
      .drive(tableView.rx.items(dataSource: dataSource)) 
      .addDisposableTo(disposeBag) 

    } 

    @IBAction func removeLastTableViewSection() { 
     // or you can change the sections manually. 
     sections.value.removeLast() 
    } 
} 

あなたがsections.valueを変更するとUIが自動的に更新されます。

これがあなたを助けてくれることを願っています。

+0

ありがとうございました!変数を使用すると、それは完全に動作します:) – jonaszmclaren

+0

@ beeth0venあなたは同様の問題[ここ](http://stackoverflow.com/questions/42744360/observable-array-to-any-array)で私を助けてくれますか? Call関数で言及したようにObservableを.justに変換します。 –

+0

'変数 'を使うことは、特にステートフルな環境を作り直したので、問題を解決するための特に反応的な方法ではありません。 'tap'イベントを聞き、それに応じて' sections'変数を定義する方が良いでしょう。 – RamwiseMatt

関連する問題