Praveen P.
Praveen P.

Reputation: 1096

Create Retrofit service class Kotlin

What would be the most appropriate way of creating a retrofit instance?(not necessarily between the 3 options below) What are the differences between these 3 ways?

Option 1

object BuffApi {
    val retrofitService : BuffApiService by lazy {
        retrofit.create(BuffApiService::class.java)
    }
}

Option 2

object BuffApi {
    val retrofitService2: BuffApiService = retrofit.create(BuffApiService::class.java)
}

Option 3

class BuffApi {
    val retrofitService: BuffApiService = retrofit.create(BuffApiService::class.java)
}

Upvotes: 2

Views: 647

Answers (1)

ObinasBaba
ObinasBaba

Reputation: 530

If there is a chance that you don't call retrofitService , or if it's not frequent it is best to Use Option 1 - val retrofitService : BuffApiService by lazy { because your program will not initalize the variable retrofitService until you access or call it which reduce the memory usage.

in another case Option_2 will help because it is static you don't have to create a new object every time you want to access it and also it is good practice to use a single instance of Service like (retrofit, repository) classes.

The ByteCode generation of Option_2 and Option_3 is almost the same: 40 and 64 line: but for Option_1 it is around 146 line

Upvotes: 2

Related Questions