RxSwift MVVM How to configure a model with a product manager?

Say I have a SwiftRx (2.0.0-beta.4) MVVM situation:

I have 4 things:

  • ItemListViewController
  • ItemsViewModel
  • ItemsManager
  • Paragraph

The Manager element has an items () function that returns items in the observed RxSwift method.

ItemsViewModel only needs to pass items. Later, perhaps, apply the display logic of the Item attribute for the View Controller interface (for example, display the date correctly).

ItemListViewController places items in a table, one item per row.

An element has 4 attributes (e.g. identifier, date, ...) that will be displayed in the table row cell.

How to configure it in ItemsViewModel and ItemsManager so that when adding, deleting and changing items in the manager, they move through the ItemsViewModel?

Looking at the documentation and looking at Rx.playground , it seems that the thing to use at the moment is the RxSwift PublishSubject <Element> or, possibly, the RxSwift map that is somehow subscribed to controls ()

How to do it well?

There is something like this in the ItemsManager right now:

func items() -> Observable<Item> { // placeholder for now return [Item(identification: "123", content: ""), Item(identification: "456", content:""), Item(identification: "789", content:"")].toObservable() } 

The view model has the following in it:

 let items = Variable(/* how to subsribe to the items in the manager? */) 
+5
source share
1 answer

A contrived solution, known as something that demonstrates a general approach and is more understandable, is below:

 import UIKit import RxSwift import RxCocoa struct Item { let identification: String let content: String } struct ItemsManager { let items: Variable<[Item]> = Variable<[Item]>( [Item(identification: "some id1", content: "some content"), Item(identification: "some id2", content: "some more content")] ) } struct ItemsViewModel { let itemsManager = ItemsManager() let myItems:Observable<[String]> init() { myItems = itemsManager.items .map({ someArrayOfItems in return someArrayOfItems.map {$0.content } }) } } class ItemListViewController: UIViewController { @IBOutlet weak var tableView: UITableView! let itemsViewModel = ItemsViewModel() let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() itemsViewModel.myItems .bindTo(tableView.rx_itemsWithCellIdentifier("itemListCell")) { (row, element, cell) in guard let myCell: UITableViewCell = cell else { return } myCell.textLabel?.text = element } .addDisposableTo(disposeBag) } } 
+8
source

Source: https://habr.com/ru/post/1237700/


All Articles