These are chat archives for ReactiveX/RxJava

28th
Aug 2017
Jacob Kristhammar
@jacobk
Aug 28 2017 06:28
Any suggestions on how to do the following without relying on errors for control flow?
        Single<RbmAccessToken> accessToken = accessTokens.get(agent);

        return Single.just(accessToken)
            .flatMap(t -> t == null
                    ? Single.error(new Throwable("no token"))
                    : t)
            .flatMap(t -> Instant.now().plusSeconds(60).isAfter(t.expiresAt())
                    ? Single.error(new Throwable("token expired"))
                    : Single.just(t))
            .onErrorResumeNext(t -> {
                Single<RbmAccessToken> newAccessToken = getAccessToken(agent);
                accessTokens.put(agent, newAccessToken);
                return newAccessToken;
            });
hehe, also, the above doesn't work :D
Artem Rudometkin
@perfectplayer
Aug 28 2017 06:38
@jacobk, also thought about it. Looks like there is some overRx. Maybe it's better to break up this logic into more pieces.
Jacob Kristhammar
@jacobk
Aug 28 2017 06:40

I had the following before:

if (accessToken != null && accessToken.blockingGet().expiresAt().isAfter(Instant.now().plusSeconds(60))) {
    return accessToken;
}

Single<RbmAccessToken> newAccessToken = getAccessToken(agent);
accessTokens.put(agent, newAccessToken);
return newAccessToken;

and was trying to get rid of the blocking get

For completness here's the current version that actually works, didn't know about null not usable as values
Single<RbmAccessToken> accessToken = accessTokens.get(agent);

return Single.just(Optional.ofNullable(accessToken))
  .flatMap(t -> t.orElse(Single.error(new Throwable("no token"))))
  .flatMap(t -> t.isExpired()
      ? Single.error(new Throwable("token expired"))
      : Single.just(t))
  .onErrorResumeNext(t -> {
    Single<RbmAccessToken> newAccessToken = generateAccessToken(agent);
    accessTokens.put(agent, newAccessToken);
    return newAccessToken;
  });
Jacob Kristhammar
@jacobk
Aug 28 2017 06:46
I feel somwhat ok with using error for the expire branch, but the initial null-check feels really contrieved
Artem Rudometkin
@perfectplayer
Aug 28 2017 06:50
From the docs: > Note that if you pass null to Just, it will return an Observable that emits null as an item. Do not make the mistake of assuming that this will return an empty Observable (one that emits no items at all). For that, you will need the Empty operator.
Jacob Kristhammar
@jacobk
Aug 28 2017 06:50
Doesn't seem to be true for javarx2 it errors out on null values
@perfectplayer do you mean "overrx" as in trying to do too much with rx?
Artem Rudometkin
@perfectplayer
Aug 28 2017 06:54
Yes, but later code looks bit better. If it really works, I think you don't need to change anything