Cannot flatMap a Single trait to a Completable trait
:warning: If you don't have something to report in the following format, it will probably be easier and faster to ask in the slack channel first. :warning:
:warning: Please take you time to fill in the fields below. If we aren't provided with this basic information about your issue we probably won't be able to help you and there won't be much we can do except to close the issue :( :warning:
If you still want to report issue, please delete above statements before submitting an issue.
Short description of the issue:
Cannot flatMap a Single trait to a Completable trait
Expected outcome:
I expect that the flatMap would let me convert to a Completable trait like in the example below.
What actually happens:
I get the following error:
'flatMap' produces 'PrimitiveSequence<SingleTrait, R>', not the expected contextual result type 'PrimitiveSequence<SingleTrait, _>'
Self contained code example that reproduces the issue:
func convertExample() -> Completable {
return Single<String>.create { single in
single(.success("hello"))
return Disposables.create()
}
.flatMap({ _ -> Completable in
return Completable.empty()
})
}
RxSwift/RxCocoa/RxBlocking/RxTest version/commit
v3.4.0
Platform/Environment
- [x] iOS
- [ ] macOS
- [ ] tvOS
- [ ] watchOS
- [ ] playgrounds
How easy is to reproduce? (chances of successful reproduce after running the self contained code)
- [x] easy, 100% repro
- [ ] sometimes, 10%-100%
- [ ] hard, 2% - 10%
- [ ] extremely hard, %0 - 2%
Xcode version:
8.3.1
:warning: Fields below are optional for general issues or in case those questions aren't related to your issue, but filling them out will increase the chances of getting your issue resolved. :warning:
Installation method:
- [x] CocoaPods
- [ ] Carthage
- [ ] Git submodules
I have multiple versions of Xcode installed: (so we can know if this is a potential cause of your issue)
- [ ] yes (which ones)
- [x] no
Level of RxSwift knowledge: (this is so we can understand your level of knowledge and formulate the response in an appropriate manner)
- [ ] just starting
- [ ] I have a small code base
- [x] I have a significant code base
Hi @programmerdave ,
Yeah, you can't flatMap with completable by design. I'm not sure would it make sense to add that overload because of ambiguity, and if we started that road, we have quadratic problem on our hands. Flat map every trait with every other trait.
I understand why you would want this. Let's wait a while so I get a better feeling what are the common patterns with these new traits.
If it presents itself as something useful, we can add it later. I would rather add something little bit later, then add it easy, and then pull it out.
It would also be great if you could provide some context for this.
Hope it makes sense.
@kzaher The main reason I would want to do this is because I have a lot of Single traits on methods that fetch data from the server and I would like in some cases at a higher level in an "interactor" class to chain a bunch of server calls and just know when it's completed so I can for example hide the loading UI. For now I've had to do this:
RxSwift+SingleToCompletable.swift
extension PrimitiveSequenceType where Self.TraitType == RxSwift.SingleTrait {
func flatMapToCompletable() -> Completable {
return Completable.create { completable -> Disposable in
return self.subscribe(onSuccess: { _ in
completable(.completed)
}, onError: { error in
completable(.error(error))
})
}
}
}
In RxJava, which Single was modeled off of I think, there is a flatMap for this: http://reactivex.io/RxJava/javadoc/io/reactivex/Single.html#flatMapCompletable(io.reactivex.functions.Function)
Single by itself works great until you get to a point where you don't care about the next value.
I just realized this was a misunderstanding. I didn't really understand what Completable was doing. I'm going to go ahead and close this issue since you're right, I can't flatMap Completable. Thanks though!
I've thought about this a bit, we can do something similar like RxJava did, it makes sense, but it might take a month or two to release it.
I also stumbled upon a similar issue: I have a bunch on Completable methods and I would like to chain them in a sane way. However, it seems that it is not possible at the moment.
Single should be able to be converted into Maybe and Completable, and Completable only to Maybe (But Maybe cannot be converted to other traits).
I wrote a code something like below and it's working. It takes out the source observable once by asObservable and then convert it to other traits.
extension PrimitiveSequence where TraitType == SingleTrait {
public func asMaybe() -> PrimitiveSequence<MaybeTrait, Element> {
return self.asObservable().asMaybe()
}
public func asCompletable() -> PrimitiveSequence<CompletableTrait, Never> {
return self.asObservable().flatMap { _ in Observable<Never>.empty() }.asCompletable()
}
}
extension PrimitiveSequence where TraitType == CompletableTrait, ElementType == Swift.Never {
public func asMaybe() -> PrimitiveSequence<MaybeTrait, Element> {
return self.asObservable().asMaybe()
}
}
We have the same problem for flat mapping a Single to an Observable right?
Actually, you can just call .asObservable on the Single and then flatmap it to an Observable.
I'm struggling to understand Completables and this issue has me even more confused... Given this:
let chain = Observable<Void>.empty()
let foo = chain.flatMap { () -> Observable<Int> in
print("return 5")
return Observable.just(5)
}
foo.subscribe { event in print(event) }
I would expect "return 5" to not get printed out because a completion event doesn't call flatMap's closure... but you are expecting it to get called when a Completable sends a completion event?
Why would you expect a Completable's complete event activate flatMap's closure when a normal observable's complete event doesn't?
Exactly @dtartaglia, that's why I closed this issue a while back. A completable should rarely be used I believe because of this very reason. It makes it so much harder to use. Even in RxJava it's difficult to interchangeably use with other observables since Completables only complete and never call on next or other operators. I really hope @kzaher would just close this already. It's better to use Single or Maybe instead of this.
What about, for example, network requests that yields just success or error? The Completable trait is the best representation of an operation that just completes or fails, although I recognize that the issue making Completables able to be flatMap because of the main reason that they not produce any next event is understandable... Having network requests of Single
@minuscorp In that case I would say by defaulting to a Completable, you're basically killing the reason you use Rx. You're breaking the chain and not allowing anything after it to continue the chain. I would say until someone comes up with an EmptySingle or something like that, you can just use Single
From now on, I've been thinking of this during the last weeks, and I'm rewriting my network layer using Single, it's easy just ignoring any next value when I don't want them but the ability of apply chain operations is critical.
Jorge Revuelta Herrero Software Engineer BISITE Research Group
El 19 jul 2017, a las 18:39, David Rodriguez [email protected] escribió:
@minuscorp In that case I would say by defaulting to a Completable, you're basically killing the reason you use Rx. You're breaking the chain and not allowing anything after it to continue the chain. I would say until someone comes up with an EmptySingle or something like that, you can just use Single but that's messy too. I do think there needs to be a better way to do this but Completable is not it.
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub, or mute the thread.
@minuscorp Yes... Another way to solve the dilemma would be to materialize the Completable. Then the Event.completed would be wrapped in an Event.next, effectively turning it into a Single
@dtartaglia I feel like that would cause even more confusion.... It technically is another concept than a completable.
@programmerdave However, it handles server errors nicely. materialize also wraps the Error into a normal next event so your pipe doesn't burst when the server emits an error. Very nice...
Actually I believe that "flatmapCompletable" is totally necessary. In my case, I receive a stream from which I want to use data (Single), but the stream that goes next must not emit any value (Completable). Example:
private func addToken<T>(request : RequestBuilder<T>) -> Single<RequestBuilder<T>> {
return Single.create {
request.addHeaders([TokenRepository.headerKey : TokenRepository.sharedInstance.token!])
$0(.success(request))
return Disposables.create()
}
}
func secureRequest(request : RequestBuilder<Void>) -> Completable {
return self.addToken(request: request)
.flatMap {
self.executeRequest(request: $0)
}
}
func executeRequest(request : RequestBuilder<Void>) -> Completable {
return Completable.create(subscribe: { (observer) -> Disposable in
request.execute({ (response, error) in
guard response != nil else {
let error = error ?? WebServiceError.unknown
observer(.error(error))
return
}
observer(.completed)
})
return Disposables.create()
})
}
I have been using RxJava2 and I think they manage better what is related to the changes between observable types than RxSwift... Single to Maybe, Single to Completable, flatmapCompletable, etc.
Here is an other use case I have for the same thing:
- Edit image on background thread -> Single< UIImage >
- Upload image to server -> Completable
Would be really nice to be able to properly do this without hacking around. I am currently converting the single event to an observable with asObservable() which isn't that bad but a bit dirty.
It seems to me that there is a general feeling that using Single is preferred in all practical cases. My experience aligns with this, so let's close this for now.