嘿,我在 android 的 kotlin flow 中工作。我注意到我的 kotlin 流程 collectLatest
调用了两次,有时甚至更多。我试过这个answer但这对我不起作用。我在我的 collectLatest
函数中打印了日志,它打印了日志。我正在添加代码
MainActivity.kt
class MainActivity : AppCompatActivity(), CustomManager {
private val viewModel by viewModels<ActivityViewModel>()
private lateinit var binding: ActivityMainBinding
private var time = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setupView()
}
private fun setupView() {
viewModel.fetchData()
lifecycleScope.launchWhenStarted {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.conversationMutableStateFlow.collectLatest { data ->
Log.e("time", "${time++}")
....
}
}
}
}
}
ActivityViewModel.kt
class ActivityViewModel(app: Application) : AndroidViewModel(app) {
var conversationMutableStateFlow = MutableStateFlow<List<ConversationDate>>(emptyList())
fun fetchData() {
viewModelScope.launch {
val response = ApiInterface.create().getResponse()
conversationMutableStateFlow.value = response.items
}
}
.....
}
我不明白为什么要调用两次。我正在附加日志
2022-01-17 22:02:15.369 8248-8248/com.example.fragmentexample E/time: 0
2022-01-17 22:02:15.629 8248-8248/com.example.fragmentexample E/time: 1
如您所见,它调用了两次。但是我加载的数据比它调用的数据多两倍。我不明白为什么它不止一次调用。有人可以指导我做错了什么。如果您需要完整代码,我将添加我的项目 link .
最佳答案
您使用的是 MutableStateFlow
源自 StateFlow
, StateFlow
具有初始值,您将其指定为 emptyList
:
var conversationMutableStateFlow = MutableStateFlow<List<String>>(emptyList())
所以第一次在 collectLatest
block 中获取 data
时,它是一个空列表。第二次是来自响应的列表。
当您调用 collectLatest
时,conversationMutableStateFlow
只有初始值,它是一个空列表,这就是您首先接收它的原因。
您可以将 StateFlow
更改为 SharedFlow
,它没有初始值,因此您将在 collectLatest
block 中仅获得一次调用。在 ActivityViewModel
类中:
var conversationMutableStateFlow = MutableSharedFlow<List<String>>()
fun fetchData() {
viewModelScope.launch {
val response = ApiInterface.create().getResponse()
conversationMutableStateFlow.emit(response.items)
}
}
或者如果你想坚持StateFlow
,你可以filter
你的数据:
viewModel.conversationMutableStateFlow.filter { data ->
data.isNotEmpty()
}.collectLatest { data ->
// ...
}
关于android - 为什么在 kotlin 中流对方付费电话两次以上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70748112/