OkHttpInterceptor navigating from kotlin interceptor to login fragment

Viewed 1196

Im struggling here a little bit.

What i am trying to achieve is to navigate from a Httpinterceptor back to the login fragment if a 401 occurs.

Im using Jwt for authorization and if the token is not valid anymore a 401 unauthorized will be returned from the backend.

I've tried googling the issue but ended up with no real answer to my problem.

What i've tried to do so far is getting the navcontroller by NavHostFragment.findNavController and by findNavController(MainActivity.activity, 1).

Both things didnt work since the first one requires you to provide a fragment which i dont have in the Interceptor and the second one failed because i couldnt figure out a way to access the MainActivity from the interceptor.

Dont have much code but this is how the interceptor looks right now (not working for obvious reasons)

package de.wabi.vistascraper.library.http.interceptors

import androidx.navigation.Navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import de.wabi.vistascraper.MainActivity
import de.wabi.vistascraper.ui.main.MainFragment
import okhttp3.Interceptor
import okhttp3.Response

class ErrorInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var builder = chain.request().newBuilder()

        var response = chain.proceed(builder.build())

        var test = NavHostFragment.findNavController(this.);

        if(response.code == 401){
           // var test = findNavController(MainActivity.activity, 1)

        }
        return response;
    }
}

Maybe on of you people around the internet have an idea.

Thanks in advance

David

1 Answers

You could do something like this to tie up you interceptor and activity:

class ErrorInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        var builder = chain.request().newBuilder()

        var response = chain.proceed(builder.build())

        if (response.code == 401) {
            GlobalNavigator.logout()
        }

        return response
    }
}

object GlobalNavigator {

    private var handler: GlobalNavigationHandler? = null

    fun registerHandler(handler: GlobalNavigationHandler) {
        this.handler = handler
    }

    fun unregisterHandler() {
        handler = null
    }

    fun logout() {
        handler?.logout()
    }
}

interface GlobalNavigationHandler {
    fun logout()
}

class YourActivity : GlobalNavigationHandler {
    override fun logout() {
        findNavController().navigate(R.id.loginFragment)
    }

    override fun onStart() {
        GlobalNavigator.registerHandler(this)
    }

    override fun onStop() {
        GlobalNavigator.unregisterHandler()
    }
}
Related