在 observable 中处理一次性用品的正确方法

Proper way to dispose of a disposable within an observable

我有一个 HTTPService,其中 returns 一个 Observable<NSData>。我的目标是将该服务组合到另一个服务中,ServiceA 为我的用例转换该数据。在 ServiceA 中使用 RxSwift 2.0.0-rc.0 中的 Observable.create 就够直接了。我的问题是如何正确处理从 HTTPService 的订阅返回的一次性用品。

如果我什么都不做,我会收到 result of call is unused: http://git.io/rxs.ud 的编译时警告。我从阅读中了解到,如果我什么都不做,可能没问题:(下面提到的 xslet xs: Observable<E> ....

In case xs terminates in a predictable way with Completed or Error message, not handling subscription Disposable won't leak any resources, but it's still preferred way because in that way element computation is terminated at predictable moment.

所以这就是我目前处理它的方式,以及我想知道我是否正确地做这件事或者我是否误解了什么。

public struct ServiceA{

    public static func changes() -> Observable<ChangeSet>{
        return Observable.create{ observable in

            // return's Observable<NSData>
            let request = HTTPService.get("https://httpbin.org/get")

            let disposable = request.subscribe(
                onNext: { data in
                    // Do more work to transform this data
                    // into something meaningful for the application.
                    // For example purposes just use an empty object
                    observable.onNext(ChangeSet())
                    observable.onCompleted()
                },

                onError:{ error in
                    observable.onError(error)
                })

            // Is this the right way to deal with the
            // disposable from the subscription in this situation?
            return AnonymousDisposable{
                disposable.dispose()
            }
        }
    }
}

documentation所说

subscribe function returns a subscription Disposable that can be used to cancel computation and free resources.
Preferred way of terminating these fluent calls is by using .addDisposableTo(disposeBag) or in some equivalent way. When disposeBag gets deallocated, subscription will be automatically disposed.

实际上你的例子在规则方面看起来不错,但它很糟糕;)(也可以,如果你只是return这个disposable):

public static func changes() -> Observable<ChangeSet>{
        return Observable.create{ observable in

            // return's Observable<NSData>
            let request = HTTPService.get("https://httpbin.org/get")

            return request.subscribe(
                onNext: { data in
                    // Do more work to transform this data
                    // into something meaningful for the application.
                    // For example purposes just use an empty object
                    observable.onNext(ChangeSet())
                    observable.onCompleted()
                },

                onError:{ error in
                    observable.onError(error)
                    })
}

但是当你 returning Observeble 我想知道,你为什么不直接使用 map 运算符?

在您的示例中,它将是这样的:

public static func changes() -> Observable<ChangeSet> {
    return HTTPService.get("https://httpbin.org/get")
                      .map(ChangeSet.init)
}