3

I am developing Huawei HarmonyOS app, and I am trying to implement a base class for background tasks with RxJava. My problem is that I don't know how to observe on the main thread.

On regular Android I would use AndroidSchedulers.mainThread().

But what can I use on HarmonyOS, respectively basic java application?

public abstract class BaseUseCase<I, O> {

    private final CompositeDisposable disposables;

    public BaseUseCase() {
        this.disposables = new CompositeDisposable();
    }

    /**
     * Builds an {@link Observable} which will be used when executing the current {@link BaseUseCase}.
     */
    public abstract Observable<O> observable(I input);


    /**
     * Executes the current use case.
     *
     * @param observer {@link DisposableObserver} which will be listening to the observable build
     * by {@link #observable(I)} ()} method.
     * @param input Parameters (Optional) used to build/execute this use case.
     */
    public void execute(DisposableObserver<O> observer, I input) {
        Preconditions.checkNotNull(observer);
        final Observable<O> observable = observable(input)
                .subscribeOn(Schedulers.io())
                .observeOn( ??? );                <- What here???
        addDisposable(observable.subscribeWith(observer));
    }


    /**
     * Dispose from current {@link CompositeDisposable}.
     */
    private void addDisposable(Disposable disposable) {
        Preconditions.checkNotNull(disposable);
        Preconditions.checkNotNull(disposables);
        disposables.add(disposable);
    }

Ps. I used architecture concept by Fernando Cejas https://fernandocejas.com/blog/engineering/2014-09-03-architecting-android-the-clean-way/

Maros Zelo
  • 53
  • 7
  • 2
    I'm not familiar with HarmonyOS. Based on docs, It has a `TaskDispatcher uiTaskDispatcher = getUITaskDispatcher();` and `TaskDispatcher` has a `asyncDispatch` method. I presume you can implement a `java.util.concurrent.Executor` over it and hand it to `Schedulers.from` without too much trouble. – akarnokd Jul 21 '22 at 15:05

1 Answers1

1

Thanks akarnokd for the answer! Seems working.

For clarification, I inject UiExecutor in BaseUseCase and use it as:

.observeOn(Schedulers.from(uiExecutor));

@Singleton
public class UiExecutor implements Executor {

    TaskDispatcher dispatcher;

    @Inject
    public UiExecutor(AbilityPackage abilityPackage) {
        this.dispatcher = abilityPackage.getUITaskDispatcher();
    }

    @Override
    public void execute(Runnable runnable) {
        dispatcher.asyncDispatch(runnable);
    }
}
Maros Zelo
  • 53
  • 7