代码之家  ›  专栏  ›  技术社区  ›  user3139545

RxJava/RxKotlin根据子类型拆分流

  •  0
  • user3139545  · 技术社区  · 8 年前

    ResponseMessage 可以是不同的子类型。我想把流分割成流,在那里我可以在自己的流中处理每种类型。

    我的第一次尝试导致了这一点,我看不出有什么效果。

    file.readLines()
            .toObservable()
            .map { mapper.readValue(it, ResponseMessage::class.java) }
            .groupBy { when(it) {
                is MarketChangeMessage -> it::class
                else -> it::class
            }}
            .map { it.????? } //How can possible this work?
    

    我现在的问题是: 将流划分为一个特定子类型的流的惯用方法是什么?

    1 回复  |  直到 7 年前
        1
  •  3
  •   ESala    8 年前

    你可以使用 ofType 操作员:

    ofType()只从源可观察到的属于特定类的项发出。

    val messages = file.readLines()
        .toObservable()
        .map { mapper.readValue(it, ResponseMessage::class.java) }
        .share() // <-- or other multicasting operator
    
    messages
        .ofType(MarketChangeMessage::class)
        .subscribe()
    
    messages
        .ofType(Other::class)
        .subscribe()