简体   繁体   中英

how to convert asynchronous promise code to rxjava

I have the following synchronous code that I would like to model as async code in RXJava.

void executeActions(List<Action> action) {
  if (action == null || action.size() == 0) return;
  for (Action action: actions) { 
     executeActions(action.handle());
  } 
}


class Action {

   //implementation of handle 
   // return List<Action> or null. 
   List<Action> handle() {
   } 
} 

Now in JS I can model this interaction with Promises like so. (Pseudo code below - my JS is weak)

executeActionsAsync(actions) { 
  var p = Promise.resolve(); 
  action.forEach(function(action) { 
    p = p.then(function() { 
           action.handle();    
        })
  } 
  return p; 
} 


class Action() { 
  function handle() { 
    actions = [];// some array of actions. 
    executeAsync(actions);
  } 
} 

I would like to model the same in RXJava2. Any help is appreciated.

First of all, Sorry for my bad English.

I edited entire answer because I did not catch what his question is.

I don't know how implement of your Action class's handle function, However this function return value should change to RxJava2's async classes. In this case, Maybe class.

  1. You wants how to implements recursion of async.
  2. Handle List or null.

Use Maybe if you want to handle something or null. in RxJava2

class Action {
  Maybe<List<Action>> handle() {}
}

This is what your Action class's handle returns.

void executeActions(Maybe<List<Action>> rxactions) {
  // add null check.
  // List<Action> handles as stream, but you can use for or iterator or whatever you want.
  rxactions.subscribe(actions -> actions.stream().map(action -> executeActions(action.handle())));
}

Important thing is, handle() function returns properly.

Additional

In RxJava2, There are multiple classes to handle async. Single, Flowable, Observable, Completable. And each classes instance method, subscribe.

Simply say,

1.Single => returns single class.

2.Flowable, Observable => returns multiple classes. (Flowable is more complex than Observable, which added back pressure.)

3.Completable => returns nothing, just succeed or not.

4.Maybe is returns * or null.

5.subscribe is execute this async.

:: Each classes can convert easily.

:: And There are so many ways to solve one problem. so it is just reference.

ex) Single<List<Foo>> <=> Flowable<Foo> // This is not same. but treat as similar.

PS.

I had this experience too. I think you need to learn more about RxJava2 to use properly everywhere.

Promise can devide into Single, Flowable, Observable, Completable. As describe above. This is the KEY to start understanding RxJava2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM