Reputation: 2263
What is the right RxJava operator for the following scenario :
I want to check if I have a token stored, if not get it from the network and use it to perform another network request.
I think it should be done with and/then/when
or with a combination of filter
and flatMap
but not sure how.
Upvotes: 1
Views: 85
Reputation: 13471
I don't know if this is what you´re looking for, but the structured should be pretty simple
Observable.just(getToken())
.filter(token->Strings.isNullOrEmpty(token))
.map(this::findNewToken)
.cache()
.subscribe(token -> println("Your new Token")
Upvotes: 1
Reputation: 13321
There are many ways to solve this. One more general solution would be Observable.concat
.
// Our sources (left as an exercise for the reader)
Observable<Data> memory = ...;
Observable<Data> disk = ...;
Observable<Data> network = ...;
// Retrieve the first source with data
Observable<Data> source = Observable
.concat(memory, disk, network)
.first();
You will need two observables for your case. If the token exists in the local storage concat
won't subscribe to the network observable. More info in the blog post.
Code sample from this blog post.
Upvotes: 2