如何将所有Retrofit网络代码归为一个单独的类,并在不发生紧密耦合或内存泄漏的情况下传达响应? MVVM

问题描述

我有一堂课,涉及使用翻新来处理所有联网操作,如下所示:

public class Networking{

public static void getCustomers(final PreviewCustomersviewmodel previewCustomersviewmodel) {
        final Call<List<Customer>> getCustomersCall = service.getCustomers();

        getCustomersCall.enqueue(new Callback<List<Customer>>() {
            @Override
            public void onResponse(@NonNull Call<List<Customer>> call,@NonNull Response<List<Customer>> response) {
                if (response.isSuccessful()) {
                    previewCustomersviewmodel.selecteddistCustomers = response.body();
                    previewCustomersviewmodel.isCustomerListRetrieved.setValue(true);
                    //Send broadcast Msg
                } else {
                    previewCustomersviewmodel.isCustomerListRetrieved.setValue(false);
                   //Send broadcast Msg
                }
            }

            @Override
            public void onFailure(@NonNull Call<List<Customer>> call,@NonNull Throwable t) {
                  previewCustomersviewmodel.isCustomerListRetrieved.setValue(false);
                  //Send broadcast Msg
            }
        });
    }
}

如您所见,我将viewmodel对象的引用传递给进行网络调用方法,并在收到响应后,在该viewmodel中的Livedata对象上传达该引用。 (或使用广播消息)

但是,我认为这可能是viewmodel对象发生内存泄漏的原因,如果用户从一种活动转移到另一种活动,我会绕过该泄漏。

使用广播消息不需要我传递viewmodel对象,但这是一个方法吗?

是否有更好的方法来实现这一目标?也许使用RxJava?还是应该将Retrofit代码保留在viewmodel中?我想实施最干净的解决方案。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)