RxSwift gets a value from a single element in an observable sequence

I am trying to gradually convert my application to RxSwift / MVVM. But I think I'm doing something wrong.

In this example, I have a static table with this specific information.

    let itens = Observable.just([
        MenuItem(name: GlobalStrings.menuItemHome,      nameClass: "GPMainVC"),
        MenuItem(name: GlobalStrings.menuItemProfile,   nameClass: "GPMainVC"),
        MenuItem(name: GlobalStrings.menuItemLevels,    nameClass: "GPLevelsVC"),
    ])

I need to know the model (MenuItem) and index when the user selects a cell, but I am having problems with this.

 tableView.rx
        .itemSelected
        .map { [weak self] indexPath in
            return (indexPath, self?.modelView.itens.elementAt(indexPath.row))
        }
        .subscribe(onNext: { [weak self] indexPath, model in

            self?.tableView.reloadData()

            //can´t get MenuItem because model its a observable
            //self?.didSelect((indexPath as NSIndexPath).row, name.nameClass)

        })
        .addDisposableTo(disposeBag)

Thanks in advance

+4
source share
1 answer

You need to take the following steps:

  • Use a variable. I think this is the best solution in your situation.

    let itens = Variable([
        MenuItem(name: GlobalStrings.menuItemHome, nameClass: "GPMainVC"),
        MenuItem(name: GlobalStrings.menuItemProfile, nameClass: "GPMainVC"),
        MenuItem(name: GlobalStrings.menuItemLevels, nameClass: "GPLevelsVC"),
    ])
    
  • Use the following code if you want to get the index and model from a clicked cell.

    tableView.rx
    .itemSelected
    .map { index in
        return (index, self.items.value[index.row])
    }
    .subscribe(onNext: { [weak self] index, model in
        // model is MenuItem class
    })
    .addDisposableTo(disposeBag)
    

    , . , , RxSwift . !

+5

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


All Articles