Skip to content

Interceptor

Season edited this page Dec 8, 2023 · 1 revision

Basic Usage

The interceptor can intercept and process the current navigation data before navigation, and can realize the functions such as security check or destination dynamic replacement.

The interceptor interface is defined as follows:

interface Interceptor {
    suspend fun shouldIntercept(
        context: Context,
        destinationData: DestinationData
    ): Boolean
    
    suspend fun intercept(
        context: Context, 
        destinationData: DestinationData
    ): DestinationData
}

You can create a custom interceptor by implementing the Interceptor API.

The shouldIntercept method is used to determine if the current navigation needs to be intercepted, returning true to indicate that it needs to be intercepted, and false to indicate that it does not need to be intercepted.

The intercept method is executed only when true is returned by shouldIntercept, and deals with the specific interception logic. Use the returned DestinationData to determine the new navigation destination, or simply throw an exception to cancel the navigation.

For example:

class TestInterceptor: Interceptor{
    override suspend fun shouldIntercept(
        context: Context,
        destinationData: DestinationData
    ): Boolean {
        // When the destination of the navigation is the release page, if you are not logged in, intercept
        if (destinationData.route.contains("publish")){
            if (!isLogin){
                return true
            }
        }
        return false
    }

    override suspend fun intercept(
        context: Context,
        destinationData: DestinationData
    ): DestinationData {
        //Replace the destination with the login page
        return destinationData.copy(route = "scheme://login")
    }
}

Global Interceptor

You can add a global interceptor through ButterflyCore, which works for all navigation.

ButterflyCore.addInterceptor(TestInterceptor())

Local Interceptor

In addition to the global interceptor, each navigation can also add a local interceptor that works only for the current navigation.

Butterfly.of(context)
    .addInterceptor(TestInterceptor())
    .navigate(Destinations.DESTINATION_TEST)

The processing order of the global interceptor and the local interceptor is to give priority to the global interceptor and then to the local interceptor.

Skip Global Interceptor

You can use the skipGlobalInterceptor method to make a navigation skip the global interceptor.

Butterfly.of(context)
    .skipGlobalInterceptor()
    .addInterceptor(TestInterceptor())
    .navigate(Destinations.DESTINATION_TEST)