Search code examples
javaandroidmvvmviewmodelrx-java2

RxJava - where in ViewModel I have to write threads for the method?


I have: In Dao:

    @Query("SELECT * FROM person_table WHERE status = :status_mudak ORDER BY RANDOM() LIMIT 5")
    Single<List<Person>> getFivePersonsFrom(String status_mudak);

In Repo:

public class PersonRepository {
    public Single<List<Person>> getFivePersonsFrom(String status_mudak) {
        return mPersonDao.getFivePersonsFrom(status_mudak);
    }
}

In ViewModel:

public class PersonViewModel extends AndroidViewModel {
    private PersonRepository mRepository;
    //declaring variables
    public PersonViewModel(@NonNull Application application) {
        super(application);
        mRepository = new PersonRepository(application);
        //initializing variables
    }
    //methods
}

Where in ViewModel I have to allocate threads, to handover method further to LiveData?


Solution

  • public class PersonViewModel extends AndroidViewModel {
    private PersonRepository mRepository;
    private MutableLiveData<List<Person>> mPersonList = MutableLiveData<List<Person>>();
    //declaring variables
    public PersonViewModel(@NonNull Application application) {
        super(application);
        mRepository = new PersonRepository(application);
        //initializing variables
    }
    
    LiveData<List<Person>> getPersonList() {
        return mPersonList;
    }
    
    private void extractPersonList() {
        mRepository.getFivePersonsFrom("some_mudatskiy_status")
            .observeOn(/*rxSchedulers.main*/)
            .subscribe(this::updatePersonList);
    }
    
    private void updatePersonList(List<Person> personList) {
        mPersonList.postValue(personList);
    }
    //methods
    

    }