SettingsViewModel
Код: Выделить всё
@HiltViewModel
class SettingsViewModel @Inject constructor(
private val myRepository: MyRepository
) : ViewModel() {
val setting1State : StateFlow = myRepository.getSetting1().stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5000),
""
)
val setting2State : StateFlow = myRepository.getSetting2().stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5000),
""
)
}
Код: Выделить всё
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private val settingsViewModel: SettingsViewModel by viewModels()
private var setting1 = ""
private var setting2 = ""
val socket : BluetoothSocket? by lazy (LazyThreadSafetyMode.NONE) {
...
}
onSettingsReceived() {
if (setting1 != "" && setting2 != "") {
lifecycleScope.launch (Dispatchers.IO) {
...
socket.connect()
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
launch {
settingsViewModel.setting1State.collect {
setting1 = it
onSettingsReceived()
}
}
launch {
settingsViewModel.setting2State.collect {
setting2 = it
onSettingsReceived()
}
}
}
}
}
}
Есть идеи, как это улучшить?
Подробнее здесь: https://stackoverflow.com/questions/790 ... -viewmodel
Мобильная версия