MaaAn13
MaaAn13

Reputation: 258

RxJava2 - execute call synchronously

I've a TestService, where I do an async task to get my data. I would like to wait for the response before I continue.

public List<Data> getData() {
    List<Data> data = new ArrayList<>();

    Disposable disposable = repository.getDataFromApi(false)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe( newData -> {
                data.addAll(newData);
            }, __ -> { });
    mCompositeDisposable.add(disposable);

    //Here I want to stop till "Data" arraylist is filled with data 

    ... do something with data        
}

In Volley I could just call req.executeSynchronously(); to make it happen. As getData() have to return data already, I've to somehow make it wait till I get response. How to do it? I'm using Single.

My approach using getBlocking();


public List<Data> getData() {
    List<Data> data = new ArrayList<>();

    Disposable disposable = repository.getDataFromApi(false)
            .observeOn(AndroidSchedulers.mainThread())
            .blockingGet();
            .subscribe( newData -> {
                data.addAll(newData);
            }, __ -> { });
    mCompositeDisposable.add(disposable);

    //Here I want to stop till "Data" arraylist is filled with data 

    ... do something with data        
}

It says cannot resolve method subscribe, so I'm probably calling it wrong..

fun getDataFromApi(): Single<List<Data>> {
    return service.getData()
            .map { jsonApiObject ->
                ...
                return@map data
            }
}

Upvotes: 2

Views: 3153

Answers (1)

michalbrz
michalbrz

Reputation: 3494

Hopefully you are aware that blocking is a strong antipattern in RxJava and you should avoid blocking whenever you can.

Saying that, if you really need to block, you have two options:

  • use blockingGet() which - as the name indicates - blocks current thread and directly returns value of publisher (Single in your case). This is probably what you were looking for. In your case:

    newData = repository.getDataFromApi(false).blockingGet();
    data.addAll(newData);
    
  • synchronize with Java classes, like CountDownLatch - more complicated and I would use blockingGet() because it's more straightforward. But it's a possibility.

Upvotes: 5

Related Questions