Search code examples
androidkotlindagger-2kotlin-extension

Kotlin extension function with request to rest server


I'm setting up extension function for Timber. I want to have kind of function to send log to my server.

The problem for me is Dagger. I have instance of RestService class in dagger and I'm using it in my whole app. But to use it I need inject somewhere this RestService. I can't do it in constructor because I haven't it.

I want to have something like this:

fun Timber.serverLogDebug(log: String) {
    restService.log(log)
}

Is it probably at all? It will be convenience for me to use my mechanism like simple Timber.d(). Alternatively I can call

restService.log(log)

in every place. But I have to have this instance everywhere.


Solution

  • In the file where you define the extension function, also define a "singleton" object to hold your restService instance, create a setter for it, and reference it from the logger function.

    private object ServiceHolder {
        var restService: RestService
    }
    
    fun Timber.setRestService(restService: RestService) {
        ServiceHolder.restService = restService
    }
    
    fun Timber.serverLogDebug(log: String) {
        ServiceHolder.restService.log(log)
    }
    

    Now you can "statically inject" your service instance by calling Timber.setRestService where you plant your Timber DebugTree.

    Note: If you want to log to the server every time you log (or every time you log an event of a specific level), you might be better off creating a custom Timber.Tree.