【问题标题】:Can't get first item from Single<List<T>>无法从 Single<List<T>> 中获取第一项
【发布时间】:2019-12-13 13:35:53
【问题描述】:

在一个android项目中,我有这样的说法:

import io.reactivex.Completable
import io.reactivex.Single

val itemsList: Single<List<T>> = getItems()

我需要从 itemsList 中获取第一项。

我该怎么做?

【问题讨论】:

    标签: android kotlin reactivex


    【解决方案1】:

    由于您的 SingleList&lt;Item&gt; 类型,当您将在您的 apiRepositoryObject 上获取它时 - 您的网络层对象,您将获得单个 List&lt;Item&gt; 或异常

    apiRepositoryObject.getItems()
    .subscribe(listOfItems -> {
        // The list of item should be handled here
    },Throwable::printStackTrace);
    

    【讨论】:

      【解决方案2】:
      val itemsList: Single<List<T>> = getItems()
      
      itemsList
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .map{list -> list.first()}
          .subscribeBy(
              onComplete = { firstItem -> {/* use your first item here */} },
              onError = { error -> {/* error handling */} }
          )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多