Last active
September 11, 2021 05:14
-
-
Save maxim-petlyuk/77ac3221c1776d14654374faf2985d5a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io.reactivex.Observable | |
import io.reactivex.ObservableSource | |
import io.reactivex.ObservableTransformer | |
import io.reactivex.functions.Predicate | |
import retrofit2.Response | |
enum class HttpCode(val code: Int) { | |
UNAUTHORIZED(401) | |
} | |
class RefreshTokenTransformer<T : Response<*>>(private val apiService: ApiService) : ObservableTransformer<T, T> { | |
override fun apply(stream: Observable<T>): ObservableSource<T> { | |
return stream.flatMap { response -> | |
if (response.code() == HttpCode.UNAUTHORIZED.code) { | |
val token = UserManager.getInstance().getToken() | |
synchronized(/* any singleton object */) { | |
val currentToken = UserManager.getInstance().getToken() | |
if (currentToken.equals(token)) { | |
return@synchronized apiService.refreshToken() | |
.flatMapObservable { tokenResponse: Response<TokenResponse> -> | |
/* here you have fresh token */ | |
return@flatMapObservable stream | |
} | |
} else { | |
return@synchronized stream | |
} | |
} | |
} else { | |
Observable.just(response) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment