我正在开发一个简单的github客户端,该客户端从特定的用户名检索存储库列表。
我的活动中使用此方法:
private void subscribeRepos(Observable<List<Repository>> repository) {
disposable.add(repository
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<List<Repository>>() {
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(List<Repository> list) {
adapter.setItems(list);
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>> onNext Called");
}
}));
}
这是我的翻新服务:
public class RetrofitService {
private static final String BASE_URL = "https://api.github.com/";
private RepoAPI repoAPI;
private static RetrofitService INSTANCE;
/**
* Method that returns the instance
* @return
*/
public static RetrofitService getInstance() {
if (INSTANCE == null) {
INSTANCE = new RetrofitService();
}
return INSTANCE;
}
private RetrofitService() {
Retrofit mRetrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(BASE_URL)
.build();
repoAPI = mRetrofit.create(RepoAPI.class);
}
/**
* Method that returns the API
* @return
*/
public RepoAPI getRepoApi() {
return repoAPI;
}
}
还有我的RepoAPI接口
public interface RepoAPI {
@GET("/users/{user_name}/repos")
Observable<List<Repository>> getRepositories(@Path("user_name") String userName);
}
因此,每当我主动调用subscribeRepos(mainViewModel.getRepositories("whateverusername"));
时,onNext都会按预期触发。但是,如果我在github帐户上手动创建新的存储库,则不会调用onNext
。我应该在我的github帐户上添加或删除新存储库时,不应该调用onNext
吗?
答案 0 :(得分:3)
这实际上不是反应式流如何使用翻新来处理网络请求。
有了网络请求,一旦您订阅了一个事件并接收到它的数据,就是这样。流已完成(您可以检查此日志记录onComplete
回调)。
尽管您可以使用它进行诸如map,switch,concat等操作,但它不是“实时”订阅。
如here所述:“ 使用RxJava进行改造网络调用::使用Single:因为我们的API不会一次或多次提供数据,而是一次发出所有数据因此,如果出现Observable,onCompleted()将在onNext()发生后立即跟进。”
如果您想要(几乎)实时的东西,则可以安排作业每隔几分钟(或几秒钟,或您想要的任何时间段)进行一次此api调用。注意数据泄漏和线程处理!