简体   繁体   English

在使用它之前检查来自另一个类的伴随对象是否已初始化

[英]Check if an companion object from another class is initialized before using it

I'm initializing my retrofit client in Base Application android class, and in MainActivity I'm using it to call api.我在 Base Application android 类中初始化我的改造客户端,在 MainActivity 中我用它来调用 api。 Sometimes, the api call starts before Base class could initialize my retrofit client and it crashes the app.有时,api 调用在 Base 类可以初始化我的改造客户端之前开始,并且它使应用程序崩溃。 How do I check in MainActivity before making api call that if apiInterface client is initialized or not before making the rest api call?如何在进行 api 调用之前检查 MainActivity 是否在进行其余 api 调用之前初始化了 apiInterface 客户端?

I know that we can do this to check initialization for lateinit variables in a class.我知道我们可以这样做来检查类中的 lateinit 变量的初始化。

::variable.isInitialized

But It's not working in this case as I access the static object like this BaseApp.apiInterface Here's my code:但在这种情况下它不起作用,因为我访问静态对象,如 BaseApp.apiInterface 这是我的代码:

BaseApp.kt基础应用程序

 class BaseApp : Application() {   
        companion object {     
            lateinit var apiInterfaceLogin: ApiInterface
            lateinit var apiInterface: ApiInterface   
            lateinit var okHttpClient: OkHttpClient.Builder
        }
       
     override fun onCreate() {
            super.onCreate()
            fetchPrefs()
            initData()
        }
    
     private fun initData() {           
     val interceptor = Interceptor { chain ->
                    val newRequest = chain.request().newBuilder()
                        .addHeader("app-token", Constants.APP_TOKEN)
                        .addHeader("Cache-Control", "no-cache")
                        .build()
                    chain.proceed(newRequest)
                }
                okHttpClient = OkHttpClient.Builder()
                okHttpClient.interceptors().add(interceptor)
                val client = okHttpClient.build()
    
                val retrofit: Retrofit = Retrofit.Builder()
                    .baseUrl(ApiInterface.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(client)
                    .build()
                apiInterface = retrofit.create(ApiInterface::class.java)
        }  
    }

MainActivity.kt主活动.kt

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    companion object {
        
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        checkShifts()  
    }

    private fun checkShifts() {
        val checkShiftsApiCall = BaseApp.apiInterface.startRun(BaseApp.userId)
        checkShiftsApiCall.enqueue(object : Callback<MyAvailableShiftsResponse> {
            override fun onResponse(call: Call<MyAvailableShiftsResponse>, response: Response<MyAvailableShiftsResponse>) {
               
            }

            override fun onFailure(call: Call<MyAvailableShiftsResponse>, t: Throwable) {
                }
            }
        })
    }
}

You can expose it using additional property in BaseApp companion:您可以使用BaseApp伴侣中的其他属性公开它:

val isApiInterfaceInitialized get() = ::apiInterface.isInitialized

As a side note, you can access properties of companion objects, but you need to reference them explicitly, for example:作为旁注,您可以访问伴随对象的属性,但您需要显式引用它们,例如:

BaseApp.Companion::apiInterface

Still, accessing isInitialized is disallowed from outside the object as this is considered implementation details that apiInterface is lateinit .尽管如此,不允许从对象外部访问isInitialized ,因为这被认为是apiInterfacelateinit实现细节。

Also, the main use case of lateinit is when we are sure that we initialize it before the first use.此外, lateinit的主要用例是当我们确定我们在第一次使用之前对其进行了初始化。 If you need to always/often check it before use or you use it outside the object, then regular nullable property may be a better choice.如果您需要在使用前始终/经常检查它或者在对象之外使用它,那么常规的可为空属性可能是更好的选择。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用kotlin从另一个类调用同伴内部的扩展对象? - How to call extension object inside companion from another class using kotlin? 使用伴侣对象返回Kotlin中的类的实例 - Using companion object to return an instance of the class in Kotlin 从 class 伴侣 object 更新 textView 文本 - Update textView text from class companion object Kotlin-在另一个对象(不是类)内部可以替代伴侣对象吗? - Kotlin - any substitute for companion object inside of another object (not class)? 从另一个列表中复制要素(保存在同伴对象中)并修改它们,这也反映了对原始同伴对象的修改 - Copying elemets from another list (saved in companion object) and modfying them also reflecting modifications to the original companion object 通过同伴使用反射和 class 名称获取房间 object - Get Room object via companion using reflection and class name 在活动和应用程序 class 中使用伴侣 object 是一种好方法吗? - Is using companion object in activity and application class a good way? 从其同伴 object 扩展数据 class 时没有可见性 - No visibility when extending function for a data class from its companion object how Unit test methods of Kotlin class with private constructor, companion object and extending another class without mocking - how Unit test methods of Kotlin class with private constructor, companion object and extending another class without mocking 分类器“TelephonyManager”没有伴随的 object,因此必须在此处初始化 - Classifier 'TelephonyManager' does not have a companion object, and thus must be initialized here
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM