【问题标题】:How to return variable from observable into another observable type如何将变量从 observable 返回到另一个 observable 类型
【发布时间】:2020-03-20 09:06:59
【问题描述】:

我查询了 youtube api 并制作了几个模型来使用 gson 转换器映射 json。现在我想使用存储库模式并统一来自我的数据库和远程的返回值,但是我有一些问题要知道如何从 RxJava 中的可观察对象返回特定变量。

我这样查询api:

@GET("playlistItems?part=snippet")
fun getLatestVideosFromPlaylist(@Query("playlistId") playlistId:String, @Query("maxResults") maxResults:String): Observable<YoutubeVideosModel>

我的模型

data class YoutubeVideosModel(
    @SerializedName("items")
    val videos: ArrayList<YoutubeVideo>
)

@Entity(tableName = "video")
data class YoutubeVideo(
    @PrimaryKey(autoGenerate = true)
    val id: Int? = null,

    @SerializedName("snippet")
    val video: YoutubeVideoData
)

我的数据源界面

interface VideoDataSource {
   fun fetchVideos(playlistId:String) : Observable<ArrayList<YoutubeVideo>>
}

从我的本地数据源返回一个 youtubeVideo 的数组列表

object VideoLocalSource: VideoDataSource {

override fun fetchVideos(playlistId: String): Observable<ArrayList<YoutubeVideo>> {
    return Observable.fromCallable {
        AppDatabase.getInstance(BaseApp.INSTANCE)?.getVideoDao()!!.fetchAllVideos()
    }
  }
}

但是从我的遥控器我找不到如何返回相同的内容:

object VideoRemoteSource: VideoDataSource {

override fun fetchVideos(playlistId: String, maxResults:String): Observable<ArrayList<YoutubeVideo>> {

    YoutubeApiClient.getYoutubeService().getLatestVideosFromPlaylist(playlistId, maxResults)
            .subscribe {
                videoModel ->
                //Here cannot use return
                return ObservableFromArray(arrayOf(videoModel.videos)
            }
      }
}

【问题讨论】:

    标签: android asynchronous kotlin rx-java


    【解决方案1】:

    您遇到的困难是异步编程要求您思考的方式。在订阅回调中返回 observable 无效。因为你不知道什么时候会调用订阅者

    对于这样的情况,您希望返回异步获取的可观察对象,您可以使用如下映射。

    object VideoRemoteSource: VideoDataSource {
    
    override fun fetchVideos(playlistId: String): Observable<List<YoutubeVideo>> {
    
        return youtubeApiService.getLatestVideosFromPlaylist(playlistId, "3")
                .flatMap{
                    Observable.fromArray(it.videos)
                }
        }
    
    }
    

    【讨论】:

    • 感谢您的回答。我正在尝试将此代码转换为 kotlin,但没有可覆盖的 apply 函数,而且我看不到如何使用它。你知道如何在 kotlin 中转换它吗?
    • 我认为它与javascript的语法相同。我更新了答案
    • 所以最后在 kotlin 中,如果我这样做,它就可以工作: .flatMap{Observable.fromArray(it.videos)}
    • 您能否将编辑发送到我的代码 sn-p 以用于 kotlin 实现?对于稍后将参考此内容的每个人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 2021-02-05
    • 2018-11-21
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    相关资源
    最近更新 更多