Search code examples
javaandroidrx-javarx-java3

RxJava: how to make code working asynchronously?


Please, coorect me if I wrong in my conclusions about async work and give any suggestions how to make this work asynchronously.

This code performs setting result of calculations in grid cells. As I assume asynchronous work should display grid cells by portions. So if we have 8 cores as result we can see that 8 cells displayed and during some time another 8 and so on (in case if I set some time delay). But for now as result cells displaying become one by one.

Model:

public class ListRepository implements ListRepositoryInterface {
private final Integer insertValue = 1000000;

private HashMap<String, BaseUnit> unitMap = new HashMap<>();

@Inject
public ListRepository() {}

public PublishSubject<BaseUnit> exec(int inputNumber) {

    PublishSubject<BaseUnit> subject = PublishSubject.create();
    Observable<BaseUnit> observable = getListObservable(inputNumber)
            .subscribeOn(Schedulers.computation())
            .flatMap(resultList ->

                Observable.fromIterable(resultList)
                        .flatMap(listElem ->
                        Observable.fromArray(ListOperationName.values())
                                .map(operationElem -> {

                            ListUnit unit = new ListUnit(operationElem, listElem, 0);
                            calculate(unit, listElem);
                            unitMap.put(unit.getViewId(), unit);
                            return unit;
                        })
                )
            );
    observable.subscribe(subject);
    return subject;
}


private Observable<ArrayList<List<Integer>>> getListObservable(int inputNumber) {
    return Observable.fromCallable(() -> {

        ArrayList<List<Integer>> list = new ArrayList<>();

        Integer[] populatedArray = new Integer[inputNumber];
        Arrays.fill(populatedArray, insertValue);

        list.add(new ArrayList<>(Arrays.asList(populatedArray)));
        list.add(new LinkedList<>(Arrays.asList(populatedArray)));
        list.add(new CopyOnWriteArrayList<>(Arrays.asList(populatedArray)));

        return list;
    });
}


private void calculate(ListUnit unit, List<Integer> list) {
    try {
        TimeUnit.MILLISECONDS.sleep(50);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    double start = getTime();

    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (list) {

        switch (unit.getOperationName()) {
            case ADD_FIRST:
                list.add(0, insertValue);
                break;
            case ADD_MID:
                list.add(list.size() / 2, insertValue);
                break;
            case ADD_LAST:
                list.add(insertValue);
                break;
            case SEARCH:
                //noinspection unused
                boolean contains = list.contains(insertValue);
                break;
            case RM_FIRST:
                list.remove(0);
                break;
            case RM_MID:
                list.remove(list.size() / 2);
                break;
            case RM_LAST:
                list.remove(list.size() - 1);
                break;
        }
    }

    unit.setTime(getTime() - start);
}

private double getTime() {
    return System.nanoTime();
}

public HashMap<String, BaseUnit> getUnitMap() {
    return unitMap;
}

}

Presenter:

public void calculate(int inputNumber) {
    fragment.showAllProgressBars();

    PublishSubject<BaseUnit> subject = repository.exec(inputNumber);

        Disposable disposable = subject.observeOn(AndroidSchedulers.mainThread())
                .subscribe(unit -> {
                    fragment.setCellText(unit.getViewId(), unit.getTimeString());

                }, Throwable::printStackTrace);

}

UPD: now I made test example and trying to subscribe to subject correctly. If I use subject.onNext() it works asynchronously, but I assume this is wrong because it doesn't get to check subject.hasComplete() and get "true". See comments "TODO" below.

private void run() {

    Log.d("APP", "INIT");

    PublishSubject<String> subject = exec(1000000);
    subject.observeOn(AndroidSchedulers.mainThread())
        .subscribe(unit -> {
            Log.d("STRING RESULT = ", unit);
            if (subject.hasComplete()) {
                //TODO: this condition should work if we use observable.subscribe(subject), not subject.onNext
                Log.d("SUBJECT", "COMPLETED");
            }
        }, Throwable::printStackTrace);
}

private int insertValue = 1000000;

public PublishSubject<String> exec(int inputNumber) {
    PublishSubject<String> subject = PublishSubject.create();

    getListObservable(inputNumber)
        .flatMap(resultList -> getOperationsObservable()
        .flatMap(operationElem -> getResultListObservable(resultList)
            .map(listElem ->
                                    calculate(operationElem, listElem)
//TODO: should be smth like this, i.e. calculate.subscribe(subject)
//                        .subscribe(subject)
                                        .subscribe(subject::onNext)

                        )
                )
        ).subscribe();

    return subject;
}


private Observable<ArrayList<List<Integer>>> getListObservable(int inputNumber) {
    return Observable.fromCallable(() -> {

        ArrayList<List<Integer>> list = new ArrayList<>();

        Integer[] populatedArray = new Integer[inputNumber];
        Arrays.fill(populatedArray, insertValue);

        list.add(new ArrayList<>(Arrays.asList(populatedArray)));
        list.add(new LinkedList<>(Arrays.asList(populatedArray)));
        list.add(new CopyOnWriteArrayList<>(Arrays.asList(populatedArray)));

        return list;
    }).subscribeOn(Schedulers.computation());
}


private Observable<String> calculate(ListOperationName operationName, List<Integer> list) {
    return Observable.fromCallable(() -> {
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        double start = getTime();

        synchronized (list) {

            switch (operationName) {
                case ADD_FIRST:
                    list.add(0, insertValue);
                    break;
                case ADD_MID:
                    list.add(list.size() / 2, insertValue);
                    break;
                case ADD_LAST:
                    list.add(insertValue);
                    break;
                case SEARCH:
                    //noinspection unused
                    boolean contains = list.contains(insertValue);
                    break;
                case RM_FIRST:
                    list.remove(0);
                    break;
                case RM_MID:
                    list.remove(list.size() / 2);
                    break;
                case RM_LAST:
                    list.remove(list.size() - 1);
                    break;
            }
        }
        return Double.toString(getTime() - start);
    }).subscribeOn(Schedulers.newThread());
}

private Observable<ListOperationName> getOperationsObservable() {
    return Observable.fromArray(ListOperationName.values());
}

private Observable<List<Integer>> getResultListObservable(ArrayList<List<Integer>> list) {
    return Observable.fromIterable(list);
}

private double getTime() {
    return System.nanoTime();
}

public enum ListOperationName {
    ADD_FIRST,
    ADD_MID,
    ADD_LAST,
    SEARCH,
    RM_FIRST,
    RM_MID,
    RM_LAST;
}

Gradle:

    dependencies {
    implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
    implementation 'io.reactivex.rxjava3:rxjava:3.0.4'
}

Solution

  • If I remove .subscribeOn(Schedulers.newThread()); from the calculate(...) method in your most recent example and make the following change to exec(...), I seem to get the desired parallelism.

    public Observable<String> exec( int inputNumber )
    {
        return getListObservable( inputNumber )
                .flatMap( resultList -> getOperationsObservable()
                    .flatMap( operationElem -> getResultListObservable( resultList )
                            .flatMap( listElem -> Observable.just( listElem )
                                    .subscribeOn( Schedulers.computation() )
                                    .flatMap( __ -> calculate( operationElem, listElem )))));
    }
    

    I removed PublishSubject - it seems redundant, you can just subscribe to the resulting Observable, no?