Change approach for service, viewmodel state management for HTS profile:

This commit is contained in:
Sylwester Zielinski
2023-04-27 14:13:35 +02:00
parent 77c0d057b5
commit 38438e4af2
4 changed files with 31 additions and 2 deletions

View File

@@ -70,10 +70,27 @@ class HTSRepository @Inject constructor(
val isRunning = data.map { it.connectionState?.state == GattConnectionState.STATE_CONNECTED }
private var isOnScreen = false
private var isServiceRunning = false
fun launch(device: ServerDevice) {
serviceManager.startService(HTSService::class.java, device)
}
fun setOnScreen(isOnScreen: Boolean) {
this.isOnScreen = isOnScreen
if (shouldClean()) clean()
}
fun setServiceRunning(serviceRunning: Boolean) {
this.isServiceRunning = serviceRunning
if (shouldClean()) clean()
}
private fun shouldClean() = !isOnScreen && !isServiceRunning
internal fun setTemperatureUnit(temperatureUnit: TemperatureUnit) {
_data.value = _data.value.copy(temperatureUnit = temperatureUnit)
}
@@ -98,7 +115,7 @@ class HTSRepository @Inject constructor(
_stopEvent.tryEmit(DisconnectAndStopEvent())
}
fun clear() {
private fun clean() {
logger = null
_data.value = HTSServiceData()
}

View File

@@ -79,6 +79,8 @@ internal class HTSService : NotificationService() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
repository.setServiceRunning(true)
val device = intent!!.getParcelableExtra<ServerDevice>(DEVICE_DATA)!!
startGattClient(device)
@@ -147,6 +149,6 @@ internal class HTSService : NotificationService() {
override fun onDestroy() {
super.onDestroy()
repository.clear()
repository.setServiceRunning(false)
}
}

View File

@@ -31,6 +31,7 @@
package no.nordicsemi.android.hts.view
import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
@@ -57,6 +58,8 @@ fun HTSScreen() {
val state = viewModel.state.collectAsState().value
val deviceName = viewModel.deviceName.collectAsState().value
Log.d("AAATESTAAA", "State: $state")
val navigateUp = { viewModel.onEvent(NavigateUp) }
Scaffold(

View File

@@ -71,6 +71,8 @@ internal class HTSViewModel @Inject constructor(
val deviceName = _deviceName.asStateFlow()
init {
repository.setOnScreen(true)
viewModelScope.launch {
if (repository.isRunning.firstOrNull() == false) {
requestBluetoothDevice()
@@ -121,4 +123,9 @@ internal class HTSViewModel @Inject constructor(
private fun onTemperatureUnitSelected(event: OnTemperatureUnitSelected) {
repository.setTemperatureUnit(event.value)
}
override fun onCleared() {
super.onCleared()
repository.setOnScreen(false)
}
}