【问题标题】:RxJava - where in ViewModel I have to write threads for the method?RxJava - 在 ViewModel 中我必须为该方法编写线程吗?
【发布时间】:2020-12-22 07:27:55
【问题描述】:

我有: 在道:

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

在回购中:

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

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

我必须在 ViewModel 中的哪个位置分配线程,以将方法进一步移交给 LiveData?

【问题讨论】:

    标签: java android mvvm viewmodel rx-java2


    【解决方案1】:
    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
    

    }

    【讨论】:

    • 现在我有这个错误:不确定如何将 Cursor 转换为该方法的返回类型 .. 。似乎我不能使用 MutableLiveData ,不是吗?
    • 您不应该将光标返回 UI,您必须提取 List 并将其放入 mPersonList。你的 UI 必须像这样观察这个 LiveData: mPersonViewModel.getPersonList().observe(getViewLifecycleOwner(), this::updatePersonListView); private void updatePersonListView(List 个人) { // 更新 UI }
    • 谢谢。还有 1 个问题 - extractPersonList() 方法应该在哪里使用?
    • 当然是在 ViewModel 中。 VM 处理业务逻辑和请求/接收数据,在 MutableLiveData 中更新它,UI 观察变化
    猜你喜欢
    • 2018-05-02
    • 1970-01-01
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    相关资源
    最近更新 更多