2

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
            }
}

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I updated post with your suggestions. Maybe you can help me correct my syntax of calling blockingGet(), as I can't wrap my head around it. I added extra information about my implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.