gpt4 book ai didi

android - 如何将 Flow 转换为 StateFlow? - 安卓 Kotlin

转载 作者:行者123 更新时间:2023-12-05 05:49:06 71 4
gpt4 key购买 nike

我是学Android开发的,看到很多话题都说LiveData不推荐用了。我的意思是它不是最新的,我们应该改用 Flows。

我正在尝试使用 Flows 从 ROOM 数据库获取数据,然后将它们转换为 StateFlow,因为我知道它们是可观察的,而且我还想向它们添加 UI 状态。比如当我成功获取数据时,状态会变为 Success,如果失败,则变为 Error。

我有一个简单的练习应用程序。它存储订阅者的姓名和电子邮件,并在回收站 View 中显示它们。

我查了很多网站,如何使用stateIn方法,如何使用StateFlows和Flows但没有成功。执行此操作的最佳方法是什么?

还有什么是更新 recyclerview 适配器的正确方法?一直在MainActivity中换一个新的adapter可以吗?

这是项目(SubscriberViewModel.kt - 第 30 行): Project link

如果我做错了其他事情,请告诉我,我想学习。我感谢任何形式的帮助。

道:

import androidx.room.*
import kotlinx.coroutines.flow.Flow

@Dao
interface SubscriberDAO {

@Insert
suspend fun insertSubscriber(subscriber : Subscriber) : Long

@Update
suspend fun updateSubscriber(subscriber: Subscriber) : Int

@Delete
suspend fun deleteSubscriber(subscriber: Subscriber) : Int

@Query("DELETE FROM subscriber_data_table")
suspend fun deleteAll() : Int

@Query("SELECT * FROM subscriber_data_table")
fun getAllSubscribers() : Flow<List<Subscriber>>

@Query("SELECT * FROM subscriber_data_table WHERE :id=subscriber_id")
fun getSubscriberById(id : Int) : Flow<Subscriber>

}

View 模型:

class SubscriberViewModel(private val repository: SubscriberRepository) : ViewModel() {

private var isUpdateOrDelete = false
private lateinit var subscriberToUpdateOrDelete: Subscriber

val inputName = MutableStateFlow("")
val inputEmail = MutableStateFlow("")

private val _isDataAvailable = MutableStateFlow(false)
val isDataAvailable : StateFlow<Boolean>
get() = _isDataAvailable

val saveOrUpdateButtonText = MutableStateFlow("Save")
val deleteOrDeleteAllButtonText = MutableStateFlow("Delete all")

/*
//TODO - How to implement this as StateFlow<SubscriberListUiState> ??
//private val _subscribers : MutableStateFlow<SubscriberListUiState>
//val subscribers : StateFlow<SubscriberListUiState>
get() = _subscribers
*/

private fun clearInput() {
inputName.value = ""
inputEmail.value = ""
isUpdateOrDelete = false
saveOrUpdateButtonText.value = "Save"
deleteOrDeleteAllButtonText.value = "Delete all"
}

fun initUpdateAndDelete(subscriber: Subscriber) {
inputName.value = subscriber.name
inputEmail.value = subscriber.email
isUpdateOrDelete = true
subscriberToUpdateOrDelete = subscriber
saveOrUpdateButtonText.value = "Update"
deleteOrDeleteAllButtonText.value = "Delete"
}

fun saveOrUpdate() {
if (isUpdateOrDelete) {
subscriberToUpdateOrDelete.name = inputName.value
subscriberToUpdateOrDelete.email = inputEmail.value
update(subscriberToUpdateOrDelete)
} else {
val name = inputName.value
val email = inputEmail.value
if (name.isNotBlank() && email.isNotBlank()) {
insert(Subscriber(0, name, email))
}
inputName.value = ""
inputEmail.value = ""
}
}

fun deleteOrDeleteAll() {
if (isUpdateOrDelete) {
delete(subscriberToUpdateOrDelete)
} else {
deleteAll()
}
}

private fun insert(subscriber: Subscriber) = viewModelScope.launch(Dispatchers.IO) {
repository.insert(subscriber)
_isDataAvailable.value = true
}

private fun update(subscriber: Subscriber) = viewModelScope.launch(Dispatchers.IO) {
repository.update(subscriber)
clearInput()
}

private fun delete(subscriber: Subscriber) = viewModelScope.launch(Dispatchers.IO) {
repository.delete(subscriber)
clearInput()
}

private fun deleteAll() = viewModelScope.launch(Dispatchers.IO) {
repository.deleteAll()
//_subscribers.value = SubscriberListUiState.Success(emptyList())
_isDataAvailable.value = false
}

sealed class SubscriberListUiState {
data class Success(val list : List<Subscriber>) : SubscriberListUiState()
data class Error(val msg : String) : SubscriberListUiState()
}
}

主要 Activity :

class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var viewModel: SubscriberViewModel
private lateinit var viewModelFactory: SubscriberViewModelFactory

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
val dao = SubscriberDatabase.getInstance(application).subscriberDAO
viewModelFactory = SubscriberViewModelFactory(SubscriberRepository(dao))
viewModel = ViewModelProvider(this, viewModelFactory)[SubscriberViewModel::class.java]
binding.viewModel = viewModel
binding.lifecycleOwner = this
initRecycleView()
}

private fun initRecycleView() {
binding.recyclerViewSubscribers.layoutManager = LinearLayoutManager(
this@MainActivity,
LinearLayoutManager.VERTICAL, false
)
displaySubscribersList()
}

private fun displaySubscribersList() {
/*
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.subscribers.collect { uiState ->
when (uiState) {
is SubscriberViewModel.SubscriberListUiState.Success -> {
binding.recyclerViewSubscribers.adapter = SubscriberRecyclerViewAdapter(uiState.list) {
subscriber: Subscriber -> listItemClicked(subscriber)
}
}
is SubscriberViewModel.SubscriberListUiState.Error -> {
Toast.makeText(applicationContext,uiState.msg, Toast.LENGTH_LONG).show()
}
}
}
}
}*/
}

private fun listItemClicked(subscriber: Subscriber) {
Toast.makeText(this, "${subscriber.name} is selected", Toast.LENGTH_SHORT).show()
viewModel.initUpdateAndDelete(subscriber)
}

}

最佳答案

您可以使用 stateIn 方法将 Flow 类型转换为 StateFlow。

 private val coroutineScope = CoroutineScope(Job())
private val flow: Flow<CustomType>
val stateFlow = flow.stateIn(scope = coroutineScope)

为了将 CustomType 转换为 UIState,您可以在 Flow 上使用 transformLatest 方法。它将类似于以下内容:

stateFlow.transformLatest { customType ->
customType.toUiState()
}

您可以在其中创建扩展函数以将 CustomType 转换为 UiState,如下所示:

fun CustomType.toUiState() = UiState(
x = x,
y = y... and so on.
)

关于android - 如何将 Flow<CustomType> 转换为 StateFlow<UIState>? - 安卓 Kotlin ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70709121/

71 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com