与LiveData类似,我如何获取协程之外的流的值?

// Suspend function 'first' should be called only from a coroutine or another suspend function
flowOf(1).first()
// value is null
flowOf(1).asLiveData().value
// works
MutableLiveData(1).value

Context

我在存储库层中避免了LiveData而 Select 了Flow.然而,我需要设定、观察和收集价值,以便立即消费.后者用于OkHttp3 Interceptor中的身份验证目的.

推荐答案

Well... what you're looking for isn't really what Flow is for. Flow is just a stream. It is not a value holder, so there is nothing for you retrieve.

So, there are two major avenues to go down, depending on what your interceptor needs.

Perhaps your interceptor can live without the data from the repository. IOW, you'll use the data if it exists, but otherwise the interceptor can continue along. In that case, you can have your repository emit a stream but also maintain a "current value" cache that your interceptor can use. That could be via:

  • BroadcastChannel
  • LiveData
  • 存储库中的一个简单属性,可以在内部进行更新,并以val的形式公开

If your interceptor needs the data, though, then none of those will work directly, because they will all result in the interceptor getting null if the data is not yet ready. What you would need is a call that can block, but perhaps evaluates quickly if the data is ready via some form of cache. The details of that will vary a lot based on the implementation of the repository and what is supplying the Flow in the first place.

Kotlin相关问答推荐

Kotlin—列出具有不同T的列表之间的操作'

在Kotlin 有更好的结合方式?

如何检测一个值是否是Kotlin中的枚举实例?

collectAsState 未从存储库接收更改

Kotlin .如何用从 1 到 90 的 5 个唯一数字填充列表中的每一行?

在协程上下文中重新抛出异常

如何访问嵌套在另一个 map 中的 map 中的值(在 kotlin 中)

如何在 Android Jetpack Compose 中的画布上绘制一侧加厚的描边?

Kotlin 使用委托进行隐式覆盖

Kotlin RxJava 可空的错误

类型是什么意

Spring webflux bean验证不起作用

kotlin 扩展属性的惰性初始化器中的这个引用

如何在调试中修复 ClassNotFoundException: kotlinx.coroutines.debug.AgentPremain?

API 'variant.getJavaCompile()' 已过时

如何在使用 Gradle 的 AppEngine 项目中使用 Kotlin

使用范围的稀疏sparse值列表

在kotlin中初始化类变量的正确位置是什么

Kotlin Android:属性委托必须有一个 'getValue(DashViewModel, KProperty*>)' 方法

如何修复未解析的参考生命周期范围?