本文介绍了Android--如何从Kotlin流中读取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从一个房间数据库里得到了一系列的剧情。我可以将此流作为实时数据进行观察,没有任何问题。
但我也想在用户单击按钮时从该流中读取最后一个值。我尝试使用first()终端流运算符,但它不能编译。您能帮个忙或提点别的建议吗?
非编译尝试读取流:
bd.buttonNext.setOnClickListener {
lifecycleScope.launch {
val episode: Episode? = viewModel.episodeFlow().first() <=== Compile ERROR
Snackbar.make(bd.root, "episode ${episode?.name}", Snackbar.LENGTH_SHORT).show()
}
}
此流来自房间:
@Query("SELECT * FROM Episode WHERE id = :id")
fun getEpisode(id: Long): Flow<Episode?>
存储库:
fun getEpisode(episodeId: Long): Flow<Episode?> = dao.getEpisode(episodeId)
查看模型-ID来自StateFlow:
fun episodeFlow(): Flow<Episode?>
= episodeIdStateFlow.flatMapLatest { episodeId ->
repository.getEpisode(episodeId)
}
编译错误:
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public fun <T> Array<out TypeVariable(T)>.first(): TypeVariable(T) defined in kotlin.collections
public inline fun <T> Array<out TypeVariable(T)>.first(predicate: (TypeVariable(T)) -> Boolean): TypeVariable(T) defined in kotlin.collections
public fun BooleanArray.first(): Boolean defined in kotlin.collections
public inline fun BooleanArray.first(predicate: (Boolean) -> Boolean): Boolean defined in kotlin.collections
public fun ByteArray.first(): Byte defined in kotlin.collections
public inline fun ByteArray.first(predicate: (Byte) -> Boolean): Byte defined in kotlin.collections
public fun CharArray.first(): Char defined in kotlin.collections
public inline fun CharArray.first(predicate: (Char) -> Boolean): Char defined in kotlin.collections
public fun CharSequence.first(): Char defined in kotlin.text
作为一种变通办法,我将剧集保存在如下的实例变量中,但如果可能的话,我希望避免这样做:
var episode: Episode? = null
...
viewModel.episodeFlow().asLiveData().observe(this) { episode ->
this.episode = episode
}
...
bd.buttonNext.setOnClickListener {
Snackbar.make(bd.root, "episode ${episode?.name}", Snackbar.LENGTH_SHORT).show()
}
=更新/解决方案21/01/15=
受使用Statein的beigirad(见下面的帖子)启发的解决方案:
private val _episodeSF = episodeFlow().stateIn(viewModelScope, SharingStarted.Eagerly, null)
val episodeSF: StateFlow<Episode?>
get() = _episodeSF
fun episodeFlow(): Flow<Episode?> = episodeIdSF.flatMapLatest { episodeId ->
repository.episodeFlow(episodeId)
}
推荐答案
您可以通过stateIn扩展将流转换为StateFlow,然后使用其value
属性获取最新值。
fun episodeFlow(): StateFlow<Episode?>
= episodeIdStateFlow.flatMapLatest { episodeId ->
repository.getEpisode(episodeId)
}.stateIn(viewModelScope, SharingStarted.Lazily, initialValue)
这篇关于Android--如何从Kotlin流中读取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!