Saturday, 4 March 2023

RxJava - How to avoid this race condition?

I'm trying to insert some data into the local database on a background thread with a Completeable inside the constructor of my ViewModel

public MainViewModel() extends ViewModel {

    public MainViewModel(){
        localRepository.insertValueIntoDatabase().subscribeOn(Schedulers.io())
                    .subscribe(() -> {
                        sharedPrefManager.setAnotherValue(true);
                    }, throwable -> {
                        Timber.e(throwable, "Failed to insert into DB");
                    });
    }
}

In my MainActivity I am also calling a method after the construction of the MainViewModel that will perform a query based on the inserted value in the constructor.

viewModel = new ViewModelProvider(this).get(MainViewModel.class);
viewModel.performQueryWithValue();
public MainViewModel() extends ViewModel {

    public MainViewModel(){
        localRepository.insertValueIntoDatabase().subscribeOn(Schedulers.io())
                    .subscribe(() -> {
                        sharedPrefManager.setAnotherValue(true);
                    }, throwable -> {
                        Timber.e(throwable, "Failed to insert into DB");
                    });
    }

    public void performQueryWithValue(){
        localRepository.getValueFromDatabase().flatMapSingle(value -> {
             if(value == 0){
                return remoteRepository.performQueryOne();
             }else{
                return remoteRepositoru.performQueryTwo();
             }

        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(result-> {
                   
                    
        }, err -> {
            
        });
    }
}

If the localRepository.insertValueIntoDatabase() takes 10 seconds to insert,

How do I make the performQueryWithValue() method wait for the completion of the insert before performing the query?



from RxJava - How to avoid this race condition?

No comments:

Post a Comment