Reputation: 325
I am quite new in the reacitve world and now I have a problem:
I have two functions that returns observables:
func connect() -> Observable<Connection>
and
func execute(_ statement: Statement) -> Observable<Result>
What I now need to do is, that connect
has to run before execute
and then I have to return the result of execute
...
What I thought I will do is to run the execute
function inside of the map
function of the observable returned by connect
, like this:
public func executeFetch(_ query: Statement) -> Observable<Result> {
return self.connect()
.map({ (connection) -> Result in
return execute(query) // here is my problem because execute returns an Observable<Result>.
})
}
But because execute
returns an Observable<Result>
I get an Observable<Observable<Result>>
How can I solve this problem?
Upvotes: 1
Views: 2052
Reputation: 2281
Instead of map
, try using flatMap
. flatMap
allows you to chain the previous result into another Observable, whereas map
is more of a direct transformation of values (e.g. turning an Observable<A>
into an Observable<B>
.
There's nothing wrong with performing a bunch of synchronous work inside map
, especially if you use a Scheduler
to ensure that that work is done on an appropriate thread (e.g. .subscribeOn(ConcurrentDispatchQueueScheduler(globalConcurrentQueueQOS: .Background))
), but if you're trying to weave a second Observable into your chain then flatMap
would be the idiomatic way to do it.
Upvotes: 1