https://kotlinlang.org logo
#dagger
Title
# dagger
c

Colton Idle

05/20/2021, 5:13 AM
I'm still pretty new to dagger, but I was using multi bindings @IntoSet on my @Provides methods that provide something called
Interceptors
from okhttp library. The thing is that interceptor order matters, and so now I believe that I need to move away from IntoSet into something that allows me to dictate order. Am I missing some other api like @IntoList or something or does this basically mean that I can't/shouldn't use multi bindings for interceptors?
e

ephemient

05/20/2021, 5:34 AM
well, you could use
@IntoMap @IntKey(1)
etc. for ordering, but I don't think it's a great fit
e.g. in addition to order, you have to distinguish application interceptors and network interceptors separate despite them being the same type
w

wasyl

05/20/2021, 6:22 AM
Ordering is unfortunate IMO. One solution would be to provide your custom wrapper like
data class OrderedInterceptor(val order: Int, val interceptor: Interceptor)
and inject
Set<OrderedInterceptor>
. Then you can provide those with orders e.g. in the range of 0-100, and when adding them to
OkHttp
do
orderedInterceptors.sortedBy { it.order }.forEach { builder.addInterceptor(it.interceptor }
👍🏼 1
👍 5
t

trevjones

05/27/2021, 4:08 AM
what i do is have a
Set<Interceptor>
for those that don’t care for ordering. Then for those that do matter on ordering. us an interface.
Copy code
interface HttpClientConfigVisitor {

    /**
     * Override to influence visitation ordering.
     * Sorting is done in descending order.
     *
     * Some elements like logging needs to be last in the list so that
     * any request mutation happens before the first log entry is created.
     * This should ensure the correct request information is logged.
     */
    val affinity: Int
        get() = Int.MAX_VALUE

    fun OkHttpClient.Builder.visit()
}
then you need only implement the visitor interface to gather up and run the interceptors