Skip to content

Instantly share code, notes, and snippets.

@maxim-petlyuk
Last active September 11, 2021 05:14
Show Gist options
  • Save maxim-petlyuk/77ac3221c1776d14654374faf2985d5a to your computer and use it in GitHub Desktop.
Save maxim-petlyuk/77ac3221c1776d14654374faf2985d5a to your computer and use it in GitHub Desktop.
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