How to avoid nested Single in RxJava2

你说的曾经没有我的故事 提交于 2020-01-06 07:15:17

问题


I am fairly new in RxJava pradigm. I am doing following is leading to nested Single objects.

  tickHappened.map{
    func(it)
  }
  //I get Single<Single<ArrayList<String>>>

Here tickHappened:Single<T> and func<T>(T param):Single<ArrayList<String>>

  tickHappened.map{
    func(it)
  }
  //I get Single<Single<ArrayList<String>>>
   .map { single ->
            single.map { list ->
                list.size
            }
        }

I actually need to return Single<Int> which is the size of the Arraylist passed. I need to use map twice in the above chain which leads to Single<Single<Int>>

Is there a way to avoid nesting Singles? If I understand Rxjava, it doesn't make sense to have a Single which enclose another Single? If not, then is there a way to return Single<Int>?


回答1:


As a beginner, one thing to learn is the flatMap operator that is available all around RxJava and is the most common operator needed for solving problems:

tickHappened
    .flatMap { func(it) }
    .map { it.size() }


来源:https://stackoverflow.com/questions/49730405/how-to-avoid-nested-single-in-rxjava2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!