0

I'm new to RxSwift and I came across the next situation:

self.viewModel!.country
        .flatMapLatest { country -> Observable<City> in
            country!.cities!.toObservable()
        }
        .map { city -> SectionModel<String, String> in
            SectionModel(model: city.name!, items: city.locations!)
        }
        .toArray()
        .bindTo(self.tableView.rx_itemsWithDataSource(dataSource))
        .addDisposableTo(self.disposeBag)

Seems to me like toArray() does nothing and I don't know why. On the other hand this code does what I want. I would like to know why the previous code does not work the same way:

self.viewModel!.country
        .flatMapLatest { country -> Observable<[SectionModel<String, String>]> in
            var models = [SectionModel<String, String>]()
            for city in country!.cities! {
                models.append(SectionModel(model: city.name!, items: city.locations!))
            }
            return Observable.just(models)
        }
        .bindTo(self.tableView.rx_itemsWithDataSource(dataSource))
        .addDisposableTo(self.disposeBag)

Thanks in advance.

EDIT:

View model implementation is as follow:

class LocationViewModel {

    let country = BehaviorSubject<Country?>(value: nil)

}

Country has a property 'cities' which is an array of City.

@solidcell You must be right, if I put debug() before and after toArray() I get 2 subscriptions, one for each debug(), and 1 next event for each array item only for the before toArray() debug().

But then, why isn't it completing?

dRamentol
  • 1,010
  • 10
  • 13
  • I'm not sure why it wouldn't be completing, given what you've said. If you could post code that I'd be able to execute that shows the issue, I'd be able to help further. – solidcell May 25 '16 at 10:20

1 Answers1

0

It's probably because country!.cities for some countries doesn't terminate. toArray() will not emit any elements until the Observable completes. Only once the Observable completes does it package all of the elements into one single element as an Array. However, I can't say for certain if this is your issue, since I don't know how you've implemented country!.cities.

Try putting a .debug() in there and see if you can spot if it's because an Observable of cities isn't completing.

solidcell
  • 7,639
  • 4
  • 40
  • 59