gpt4 book ai didi

android - RxJava : How to extract same observeOn from different functions?

转载 作者:行者123 更新时间:2023-11-29 22:49:13 24 4
gpt4 key购买 nike

基本上我的 Android 应用程序有一些元数据需要在不同的情况下报告给后端服务器:

data class SearchMetaData(
val searchId: String?,
val isRateLimit: Boolean
)

为了让代码干净,我把最小的情况做成如下。所有的上报逻辑都是类似的,每个函数都订阅元数据提供者,获取需要上报的值。

fun logEvent1() {
fetchMetaData().observeOn(schedulers.mainThread()).subscribe({ metadata ->
...//lots of other events data here
val sessionMetadata = SessionMetadata()
sessionMetadata.id = metadata.searchId
sessionMetadata.limiit = metadata.isRateLimit
event1.session = sessionMetadata
...
report(event1)
})
}

fun logEvent2() {
fetchMetaData().observeOn(schedulers.mainThread()).subscribe({ metadata ->
...//lots of other events data here
val sessionMetadata = SessionMetadata()
sessionMetadata.id = metadata.searchId
sessionMetadata.limiit = metadata.isRateLimit
event2.session = sessionMetadata
...
report(event2)
})
}

fun logEvent3() {
fetchMetaData().observeOn(schedulers.mainThread()).subscribe({ metadata ->
...//lots of other events data here
val sessionMetadata = SessionMetadata()
sessionMetadata.id = metadata.searchId
sessionMetadata.limiit = metadata.isRateLimit
event3.session = sessionMetadata
...
report(event3)
})
}

我担心的是每次我们改变元数据的模式时,我们都需要更新所有的 logEventX ,我想知道我们是否可以在不同的地方提取所有的 subscribe函数并获取元数据?

最佳答案

考虑使用 compose 和 doOnSuccess 的扩展函数

Single<MetaData>.handleLogging() : Single<MetaData>{
return compose{
it.doOnSuccess{ metaData ->
val sessionMetadata = SessionMetadata()
sessionMetadata.id = metadata.searchId
sessionMetadata.limiit = metadata.isRateLimit
report(sessionMetaData)
}
}
}

//usage
fetchMetaData().handleLogging().subscribe{
//other uncommon logic here.
}

关于android - RxJava : How to extract same observeOn from different functions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58108921/

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