purcha
purcha

Reputation: 371

Invoke method only when other method are done - RxJava

I have 2 method:

private void method1() throws InterruptedException {
        //SimulateLongOperation
        Thread.sleep(5000);
        System.out.println("hello1");
    }

private void method2(){
        System.out.println("hello2");
    }

I would like to invoke method2 when method1 is done, but I don't want to block UI thread.
Is it possible to do it with RxJava ?
How will it look like? There are no simple examples on the internet, there are only great articles that I can not understand.

When I invoke:

method1();  
method2(); 

I block the main thread, it's horrible.

Upvotes: 0

Views: 102

Answers (2)

Valerii
Valerii

Reputation: 405

You also could try the following:

  • With Kotlin:
     Completable.fromAction{ method1() }
            .doOnComplete{ method2() }
            .subscribeOn(Schedulers.io())
            .subscribe()
  • With Java:
     Completable.fromAction(() -> method1() )
            .doOnComplete(__ ->  method2())
            .subscribeOn(Schedulers.io())
            .subscribe()

Upvotes: 2

Manu
Manu

Reputation: 422

Since you are looking for a really specific answer I will post a naive implementation here. Depending on your usecase there maybe better solutions.

    private void method1() throws InterruptedException {
            //SimulateLongOperation
            Thread.sleep(5000);
            System.out.println("hello1");
        }

    private void method2(){
            System.out.println("hello2");
        }

    void solution() {
      Observable<Void> first = Observable.fromCallable(() -> {
                method1();
                return null;
            });
    Observable<Void> second = Observable.fromCallable(() -> {
                method2();
                return null;
            });
    first.flatMap((Function<Void, ObservableSource<?>>) aVoid -> second)
         .subscribeOn(Schedulers.io())
         .observeOn(AndroidSchedulers.mainThread())
         .subscribe();
    }

Upvotes: 1

Related Questions