Skip to content

Instantly share code, notes, and snippets.

@bmbogdan
Last active December 13, 2022 17:23
Show Gist options
  • Save bmbogdan/d55d97421f486dcab4f78192922af13c to your computer and use it in GitHub Desktop.
Save bmbogdan/d55d97421f486dcab4f78192922af13c to your computer and use it in GitHub Desktop.
Gyroscope Android implementation using Dependency Inversion Principle
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.map
// Gyroscope data class
data class GyroscopeData(
val x: Float,
val y: Float,
val z: Float
)
// Gyroscope interface
interface Gyroscope {
fun getGyroscopeData(): Flow<GyroscopeData>
}
// Gyroscope implementation
class AndroidGyroscope(context: Context) : Gyroscope {
private val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
private val gyroscopeSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)
override fun getGyroscopeData(): Flow<GyroscopeData> = callbackFlow {
val sensorEventListener = object : SensorEventListener {
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
override fun onSensorChanged(event: SensorEvent?) {
event?.let {
trySend(
GyroscopeData(
x = it.values[0],
y = it.values[1],
z = it.values[2]
)
)
}
}
}
sensorManager.registerListener(
sensorEventListener,
gyroscopeSensor,
SensorManager.SENSOR_DELAY_NORMAL
)
awaitClose { sensorManager.unregisterListener(sensorEventListener) }
}
}
// Usage in some other class
class GyroscopeReadAndMultiplyUseCase(private val gyroscope: Gyroscope) {
fun execute(multiplicationFactor: Int) = gyroscope.getGyroscopeData().map {
it.copy(
x = it.x * multiplicationFactor,
y = it.y * multiplicationFactor,
z = it.z * multiplicationFactor
)
}
}
@bmbogdan
Copy link
Author

bmbogdan commented Dec 11, 2022

This code was generated with ChatGPT and refactored to be usable. More details can be found in my Medium article - https://medium.com/@badeamihaibogdan/clean-code-for-using-gyroscope-sensor-in-android-assisted-by-chatgpt-b68ff2a250e6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment