简体   繁体   中英

Kotlin object require init to happen again if failed

I have an object BleClient which is singleton that responsible for all my BLE operations.

When I run any function from the BleClient as intended that init is called like so:

init {
    RLog.d(TAG_BLE, "BleClient init")
    val bluetoothManager = MyApp.application.getSystemService(BluetoothManager::class.java)
    bluetoothAdapter = bluetoothManager?.adapter
    bluetoothLeScanner = bluetoothAdapter?.bluetoothLeScanner!!
}

But, when the BT is disabled the init crashes on this function:

bluetoothLeScanner = bluetoothAdapter?.bluetoothLeScanner!!

So, I did like so:

 init {
    RLog.d(TAG_BLE, "BleClient init")
    val bluetoothManager = MyApp.application.getSystemService(BluetoothManager::class.java)
    bluetoothAdapter = bluetoothManager?.adapter
    //Check if adapter is enabled        
    if (bluetoothAdapter != null && bluetoothAdapter!!.isEnabled)
        bluetoothLeScanner = bluetoothAdapter?.bluetoothLeScanner!!
}

This works, but... after the first fail the user turn BT on and then call any other function from BleClient. The init would be called again and I need it to...

So I did:

init {
    RLog.d(TAG_BLE, "BleClient init")
    val bluetoothManager = 
    MyApp.application.getSystemService(BluetoothManager::class.java)
    bluetoothAdapter = bluetoothManager?.adapter

    require(bluetoothAdapter != null && bluetoothAdapter!!.isEnabled)
    bluetoothLeScanner = bluetoothAdapter?.bluetoothLeScanner!!
}

Because I need this requirement for the init, and if it fails the init should triggered again.

But I get a crash "Caused by: java.lang.IllegalArgumentException: Failed requirement."

How to properly use the require ?

Singletons by definition are initialized only once - I don't think you can anyhow re-initialize them. You can make it just a regular class, not singleton and create it when bluetooth is already enabled. You can also keep it a singleton and do not perform initialization in a constructor, but on demand. In most cases, performing more advanced stuff in constructors isn't really a good idea.

You should also consider a case where you initialized your service when bluetooth was enabled and then user disables it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM