I'm talking to an older Android API, how can I run...
# android
r
I'm talking to an older Android API, how can I run the Looper here without running out of threads eventually? I have a feeling I'm gonna leak resources here.
Copy code
connectionScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
            Looper.prepare()
            listener = object : PhoneStateListener() {
                override fun onSignalStrengthChanged(asu: Int) {
                }

                override fun onDataConnectionStateChanged(state: Int, networkType: Int) {
                    dataState.setValue(state.toDataByteArray())
                    networkTypeC.setValue(networkType.toDataByteArray())
                }

                @SuppressLint("MissingPermission")
                override fun onServiceStateChanged(serviceState: ServiceState?) {
                    Log.d(TAG, "Service state changed to $serviceState")
                    if (serviceState != null) {
                        updateFormServiceState(serviceState)
                    }
                }
            }
            telephonyManager.listen(
                listener,
                PhoneStateListener.LISTEN_DATA_CONNECTION_STATE or
                        PhoneStateListener.LISTEN_SERVICE_STATE or
                        PhoneStateListener.LISTEN_SIGNAL_STRENGTH
            )
            Looper.loop()
        }
not kotlin but kotlin colored 4
c
you can create a
HandlerThread
and use it as the launch context.
Copy code
val handlerThread = HandlerThread("MyThread")
handlerThread.start()
val handler = Handler(handlerThread.looper)
val myDispatcher = handler.asCoroutineDispatcher()