我有来自房间数据库的情节流。我可以毫无问题地观察这个流的实时数据。
但我也想在用户单击按钮时从该流程中读取最后一个值。我尝试使用 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()
}
}
此流程来自 ROOM :
@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)
}