Observed chains

I have a set of objects, name them obj. They have a method act(). The method act()will ultimately lead to what the event()observable odoes not cause onComplete.

What is a good way to tie them together?

That is, call o.act(), wait o.event().onComplete, and then call the next o2.act(), etc. for an indefinite amount oin the collection.

So the signature is this:

public class Item {
    final protected PublishSubject<Object> event = PublishSubject.create();

    public Observable<ReturnType> event() {
        return event;
    }

    public void act() {
        // do a bunch of stuff
        event.onComplete();
    }
}

And then in the consumption code:

Collection<Item> items...
foreach item in items
  item.act -> await item.event().onComplete() -> call next item.act() -> so on
+4
source share
1 answer

If I understand correctly, your objects have this signature:

public class Item {
    public Observable<ReturnType> event()...
    public ReturnType act()...
}

So, if they were filled like this:

public class Item {

    private final String data;
    private final Observable<ReturnType> event;

    public Item(String data) {
        this.data = data;

        event = Observable
                .fromCallable(this::act);
    }

    public Observable<ReturnType> event() {
        return event;
    }

    public ReturnType act() {
        System.out.println("Item.act: " + data);
        return new ReturnType();
    }
}

Then they could be chained like this:

Item item1 = new Item("a");
Item item2 = new Item("b");
Item item3 = new Item("c");

item1.event()
        .concatWith(item2.event())
        .concatWith(item3.event())
        .subscribe();

Result:

Item.act: a
Item.act: b
Item.act: c

, Iterable, flatMap:

Iterable<Item> items = Arrays.asList(item1, item2, item3);

Observable.from(items)
        .flatMap(Item::event)
        .subscribe();

Alternative

, :

public class Item {
    private final PublishSubject<Void> event = PublishSubject.create();

    private final String data;

    public Item(String data) {
        this.data = data;
    }

    public Observable<Void> event() {
        return event;
    }

    public Void act() {
        System.out.println("Item.act: " + data);
        // do a bunch of stuff
        event.onCompleted();
        return null;
    }
}

:

Iterable<Item> iterable = Arrays.asList(item2, item3);

item1.event().
        concatWith(Observable.from(iterable)
                .map(Item::act))
        .subscribe();

item1.act();

event() 2 .

+2

Source: https://habr.com/ru/post/1665456/


All Articles