【问题标题】:Android RxJava remember variableAndroid RxJava 记住变量
【发布时间】:2016-04-29 12:07:57
【问题描述】:

我正在学习 RxJava。

我的数据:

  • 字符串变量 - 命令

我的目标:

  • 拆分字符串(空格作为正则表达式)-完成
  • 检查数组是否有元素 - 完成
  • 将数组映射成字符串(foreach)-完成
  • 重要的一点:我必须记住拆分后的第一个字符串,因为它在订阅中是必需的
  • 我知道我的第二个字符串是可选的。如果存在,那么它可能是 json 或常规字符串
  • 我必须知道第二个字符串中的内容(不存在/json/常规字符串)并执行不同的操作(订阅)。

我的代码:

Observable.just(command)
                .map(s -> s.split(" "))
                .filter(strings -> strings.length > 0)
                .flatMap(Observable::from)
//                .remember my first string
                .skip(1)
                .filter(s1 -> s1 != null)
//                .handle if s1 == null - it means that 2nd string does not exitst
                .map(this::getJson)
//                .onErrorResumeNext( * subscribe on that string element*) // regular string
//              IF getJson return JSONObject
//                .subscribe(jsonObject -> myMethod(firstString, jsonObject))

我是否以正确的方式考虑它?怎么做才合适?

【问题讨论】:

    标签: android arrays json string rx-java


    【解决方案1】:

    当你 flatMap 你的 String 数组并跳过你的第一个 String 时,你将丢失第一个 String

    如果您想使用第一个和第二个字符串,则必须同时发出它们。

    Observable.just(command)
                  .map(s -> s.split(" "))
                  .filter(strings -> strings.length > 0)
                  .flatMap(arr -> {
                      // transform the second args as a Json Object
                      Observable<Object> jsonObject = Observable.from(arr)
                                                                .skip(1)
                                                                .map(this::getJson);
    
                      // get the first String
                      Observable<String> firstArg = Observable.from(arr)
                                                              .take(1);
                      // call myMethod with the first String and the jsonObject
                      return Observable.combineLatest(firstArg, jsonObject, (first, second) -> myMethod(first, second))
                                       // call fallback method if you haven't a second arg 
                                       .switchIfEmpty(firstArg.map(f -> fallbackMethod(m)));
    
                  })
                  .subscribe();
    

    【讨论】:

      猜你喜欢
      • 2021-09-10
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2016-01-16
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 2019-08-28
      相关资源
      最近更新 更多