![](/img/trans.png)
[英]Recover the response of my service in another class with retrofit2 in kotlin
[英]Create Retrofit service class Kotlin
創建 retrofit 實例的最合適方式是什么?(不一定在下面的 3 個選項之間)這 3 種方式有什么區別?
選項1
object BuffApi {
val retrofitService : BuffApiService by lazy {
retrofit.create(BuffApiService::class.java)
}
}
選項 2
object BuffApi {
val retrofitService2: BuffApiService = retrofit.create(BuffApiService::class.java)
}
選項 3
class BuffApi {
val retrofitService: BuffApiService = retrofit.create(BuffApiService::class.java)
}
如果您有可能不調用retrofitService
,或者它不頻繁,最好使用選項 1 - val retrofitService: BuffApiService by lazy {
因為您的程序不會初始化變量retrofitService
直到您訪問或調用它減少memory 用法。
在另一種情況下,Option_2 會有所幫助,因為它是 static,您不必每次要訪問它時都創建一個新的 object,而且使用單個服務實例(如( retrofit ,存儲庫)類)也是一種很好的做法。
Option_2 和 Option_3 的 ByteCode 生成幾乎相同:40 和 64 行:但是對於 Option_1 它大約是 146 行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.