2016-08-26 12 views
1

私のアンドロイドアプリケーションは、コマンドがアプリケーション内の他のコンポーネントにコールして結果を待つ必要があるため、別のコマンドとレスポンスを非同期で処理する必要があります。RxAndroidが観測可能な状態でスイッチケースを処理する

rxjavaを使用して、受信した文字列を別のパラメータにマップしようとしましたが、別のコマンドを手動でルーティングする必要があります。ロジックをカスタマイズされた観測可能ノードにルーティングし、

コードは以下の通りです:

  Observable.just(command_string) 
      .map(new Func1<String, Command>() { 
       @Override 
       public Command call(String command_string) { 
        ......; 
       } 
      }) 
      .filter(new Func1<Command, Boolean>() { 
       @Override 
       public Boolean call(Command file) { 
        ThreadUtils.logThreadSignature(TAG); 
        return !isExcuetingCmd; 
       } 
      }) 
      .subscribeOn(Schedulers.io()) 
      .map(new Func1<Command, CmdResponse>() { 
       @Override 
       public CmdResponse call(Command command) { 
        //stupid code... 
        switch (cmd) 
        { 
         case CMD_1: 

          ... 
          CmdResponse = xxx 
          break; 

         case CMD_2: 
          ... 
          CmdResponse = xxx 
          break; 

         case CMD_3: 
          ... 
          CmdResponse = xxx 
          break;      
        } 
        return CmdResponse; 
       } 
      }) 
      .flatMap(new Func1<CmdResponse, Observable<String>>() { 
       @Override 
       public Observable<String> call(CmdResponse cmdResponse) { 
        return Observable.just(gson.toJson(CmdResponse)); 
       } 

      }); 

答えて

2

私はあなたが行うことができると思う何あなたのcmdResponseに応じて、あなたがグループにその観測可能を追加することができますので、その後、GROUPBY演算子を使用しています。最後に、観測可能な終了が出ると、加入者のグループを確認することができます。

公式ドキュメントここhttp://reactivex.io/documentation/operators/groupby.html

私はあなたがここにhttps://github.com/politrons/reactive

+0

より多くの例を見ることができます

/** * In this example we create a String/Person group. * The key of the group is just the String value of the sex of the item. */ @Test public void testGroupBySex() { Observable.just(getPersons()) .flatMap(listOfPersons -> Observable.from(listOfPersons) .groupBy(person -> person.sex)) .subscribe(booleanPersonGroupedObservable -> { switch (booleanPersonGroupedObservable.getKey()) { case "male": { booleanPersonGroupedObservable.asObservable() .subscribe(person -> System.out.println("Here the male:" + person.name)); break; } case "female": { booleanPersonGroupedObservable.asObservable() .subscribe(person -> System.out.println("Here the female:" + person.name)); break; } } }); } private List<Person> getPersons() { List<Person> people = new ArrayList<>(); people.add(new Person("Pablo", 34, "male")); people.add(new Person("Paula", 35, "female")); return people; } 

をしたことを確認し、この例ように、スイッチケースを交換するbooleanPersonGroupedObservableをカスタマイズする方法はありますコードをよりスケーラブルにすることができます。実際には、最終結果が単一の型としてエミュレートされ、異なる要求を処理するすべてのコードが別のクラスになり、加入者がフィーナ私は結果をユーザーに返します。 – iammini

+0

要件の詳細がわからないときは、私が貼り付けた文書を読み、必要に応じてチェックします – paul

関連する問題