Android 2可观察到的,单

时间:2018-07-03 09:42:58

标签: android

我试图通过在构造函数中传递单个位置和该位置的visitCount来创建新的LocationViewModel,但是为此,我首先获取所有位置,然后为每个位置尝试获取visitCount

addDisposable(mLocationProvider.getLocation()
            .flatMapSingle(locations -> Flowable.fromIterable(locations)
                    .flatMapSingle(singleLocation -> mVisitCountRepo.requestVisitCount(singleLocation.getId()))
                    .toList())
            .subscribe(visitCountList -> {


            }, Throwable::printStackTrace));

问题是我不知道如何将两者结合起来,所以我会有类似的东西:

flatMapSinge(singleLocation,visitCount -> new LocationViewModel(singleLocation,visitCount).toList()

目前,我最终获得列表,将不胜感激。

2 个答案:

答案 0 :(得分:0)

您可以使用Map或Pair类来返回visitCount和location,并一一忽略结果而不是列表。

在这里我附上了简单的kotlin和pair类的Java代码,也许对您有帮助。

科特琳课

Observable.just("Will")
  .observeOn(Schedulers.io())
  .flatMap({ name ->
    updateUserName.execute(name) //returns another Observable<ApiResult> after calling the API
  }, {
    //this is executed after resolving the last observable emitted, so the result is ready.
     name: String, apiResult: ApiResult -> Pair(name, apiResult) 
  })
  .subscribe({ result ->
    result.first //name
    result.second //apiResult
  })

Java类:

bservable.just("foo")
          .flatMap(new Func1<String, Observable<Integer>>() {
              @Override
              public Observable<Integer> call(String foo) {
                  return Observable.range(1, 5);
              }
          }, new Func2<String, Integer, Pair<Integer, String>>() {
              @Override
              public Pair<Integer, String> call(String s, Integer i) {
                  return new Pair<>(i, s);
              }
          })
          .subscribe(new Action1<Pair<Integer, String>>() {
              @Override
              public void call(Pair<Integer, String> pair) {
                  System.out.println("Result: " + pair.first + " Foo: " + pair.second);
              }
          });

答案 1 :(得分:0)

您可以像这样在结尾处获得LocationViewModel的列表

  addDisposable(mLocationProvider.getLocation().flatMap(Flowable::fromIterable)
            .flatMap(singleLocation -> mVisitCountRepo.requestVisitCount(singleLocation.getId()).toFlowable()
                    .map(visitCount -> new LocationViewModel(singleLocation, visitCount)))
            .toList()
            .subscribeWith(new DisposableSingleObserver<List<LocationViewModel>>() {
                @Override
                public void onSuccess(List<LocationViewModel> locationViewModels) {

                }

                @Override
                public void onError(Throwable e) {

                }
            }));