Last active
January 8, 2019 10:27
-
-
Save Sanjay-Prajapati/5c592f6f360fe5fe39927bbc39da70e4 to your computer and use it in GitHub Desktop.
Retrofit2 custom interceptor that parse the response from API. After that we can check status and based on that returns a same copy that other classes can consume.
This file contains hidden or 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 com.google.gson.Gson | |
import okhttp3.Interceptor | |
import okhttp3.Response | |
import okhttp3.ResponseBody | |
import org.json.JSONException | |
/** | |
* Logout Interceptor. | |
* Here i extend the BaseActivity to navigate user to another screen. i need runOnUIThread to execute navigateToLogin() method. | |
*/ | |
class LogoutInterceptor : BaseActivity(), Interceptor { | |
override fun intercept(chain: Interceptor.Chain?): Response { | |
val response: Response = chain?.proceed(chain.request())!! | |
val globJson = response.body()!!.string() | |
try { | |
/** | |
* GlobalResponse class is the API response model. | |
* status is the class member of GlobalResponse class. we will get logout session code in status. | |
* SessionInvalid variable contains the defined status code. | |
*/ | |
val globalResponse: GlobalResponse = Gson().fromJson(globJson, GlobalResponse::class.java) | |
if (globalResponse.status == SessionInvalid) { | |
runOnUiThread(object : Runnable { | |
override fun run() { | |
navigateToLogin() | |
/** | |
navigateToLogin() method's body part is defined in BaseActivity. Here AppApplication is Application class | |
val intent = Intent(AppApplication.instance.applicationContext, WelcomeActivity::class.java) | |
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK | |
intent.putExtra(SESSION_LOGOUT_REASON, true) | |
AppApplication.instance.startActivity(intent) | |
*/ | |
} | |
}) | |
} | |
} catch (e: JSONException) { | |
e.printStackTrace() | |
} | |
// Re-create the response before returning it because body can be read only once | |
return response.newBuilder() | |
.body(ResponseBody.create(response.body()!!.contentType(), globJson)).build() | |
} | |
} |
This file contains hidden or 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
/** | |
* You can call your Custom interceptor while creating OkHttpClient object | |
**/ | |
val okHttp:OkHttpClient= OkHttpClient.Builder() | |
..... | |
.addNetworkInterceptor(LogoutInterceptor()) | |
.... | |
.build() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment