英文:
How do I handle cancelling of publishers in Combine's Future functions?
问题
在RxSwift中,你可以创建一个类似下面的响应式函数:
func aFunc() -> Observable<Void> {
return Observable.create({ emitter in
let disposable = Observable
.combineLatest(someObservable,
someOtherObservable)
.subscribe(onNext: { responseA, responseB in
// 做一些操作
})
return Disposables.create {
disposable.dispose()
}
})
}
而在Combine中,你可以通过使用Future来实现类似的结果:
func aFunc() -> Future<Void, Error> {
return Future { promise in
somePublisher
.combineLatest(someObservable,
someOtherObservable)
.sink { responseA, responseB in
// 做一些操作
}
}
}
值得注意的是,Future似乎没有像RxSwift中的Disposables.create那样的等效功能来处理资源释放。在Combine中,你可以考虑使用cancellable来管理取消操作,就像这样:
let cancellable = somePublisher
.combineLatest(someObservable, someOtherObservable)
.sink { responseA, responseB in
// 做一些操作
}
// 当需要取消时,可以使用
cancellable.cancel()
这将允许你手动取消与publisher相关的订阅。你可以根据需要在适当的时机调用cancel()方法来释放资源。
英文:
In RxSwift you can create a reactive function something like this:
func aFunc() -> Observable<Void> {
return Observable.create({ emitter in
let disposable = Observable
.combineLatest(someObservable,
someOtherObservable)
.subscribe(onNext: { responseA, responseB in
// do stuff
})
return Disposables.create {
disposable.dispose()
}
})
}
In Combine you can achieve similar results using Future:
func aFunc() -> Future<Void, Error> {
return Future { promise in
somePublisher
.combineLatest(someObservable,
someOtherObservable)
.sink{ responseA, responseB in
// do stuff
}
})
}
The thing I don't quite get is that the Future doesn't seem to return its equivalent of RxSwift's
return Disposables.create {
disposable.dispose()
}
How is standard practice to handle disposing/cancelling of publishers in a Future?
I tried simply adding:
_ = somePublisher...
But then the publisher isn't kept alive and will simply not activate at all.
Should I just hook on .store(in: &cancellables) to the end of the publisher. But them, when do I cancel those cancellables? Or is there some way of returning cancellables, like in RxSwift? What am I missing?
答案1
得分: 1
答案是,你不需要这样做。一个 Combine Future 就像一个 RxSwift Single,在开始后无法取消。
英文:
The answer is, you don't. A Combine Future is like an RxSwift Single that can't be canceled once it starts.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论