将 RxSwift Observable 绑定到数组



正在尝试RxSwift并尝试转换我的网络调用。我似乎无法在视图中显示我的数据,因为我不确定如何将我的可观察量转换为我的视图可以使用的东西。这是我请求的示例:

class SomeService {
    let provider = Provider()
    func getData() -> Observable<[Object]?> { // Returns json
        return provider
            .request(.getSomething())
            .debug()
            .mapArrayOptional(type: Object.self) 
            // Using Moya_Modelmapper map each item in the array
    }
}

在我的视图控制器中,我得到数据:

 let data = Service.getData()
 print(data) ... <Swift.Optional<Swift.Array<MyApp.Item>>>

试图订阅对序列的响应,但我不知道我是如何实际将其转换为我可以在我的视图中使用的数组之类的东西。

更新:已实现答案:

    func itemsObserver() {
        print("Time to print step 1") // This gets printed
        data
        .filter { $0 != nil }.map { $0! }
        .subscribe(
            onNext: { objects in
                print(objects as Any) 
                print("Step 2") // This does not get executed at all
            },
            onCompleted:{ objects in
                print(objects as Any) // This is ()
                print("Complete") // This gets printed
            }
            ).addDisposableTo(disposeBag)
    }
    itemsObserver()

控制台输出:

 Time to print step 1
 Service.swift:21 (getData()) -> subscribed
 Service.swift:21 (getData()) -> Event next(Status Code: 200, Data Length: 141)
 Service.swift:21 (getData()) -> Event completed
 Service.swift:21 (getData()) -> isDisposed
 ()
 Complete

更新:

如果你的onNext块根本没有被调用,那是因为data从未产生过任何东西。要么您的生产者没有生产任何对象,要么mapArrayOptional没有转换它们。

onCompleted块不接受任何参数,因此您在其中拥有的objects变量是无意义的/无效的。


试试这个:

let data = service.getData()
data
    .filter { $0 != nil }.map { $0! } // this removes the optionality of the result.
    .subscribe(onNext: { objects in
        // in here `objects` will be an array of the objects that came through.
}).disposed(by: bag)

最新更新