【问题标题】:LiveData return null getting API responseLiveData 返回 null 获取 API 响应
【发布时间】:2020-11-17 09:51:54
【问题描述】:

我在没有执行 API 的情况下得到空的实时数据。 当我调用这个 repo 函数时,我得到的是 null 而不是任何响应,然后经过一段时间的延迟,我得到了 API 的响应,但没有得到任何返回值。
BottomSheetFragment

sendOTPViewModel = ViewModelProvider(this).get(SendOTPViewModel::class.java)
sendOTPViewModel.init(context)
sendOTPViewModel.setKey()
sendOTPViewModel.key.observe(viewLifecycleOwner, { key ->
            LoggerUtils.E(TAG, key)
        })


视图模型

public class SendOTPViewModel extends ViewModel {

    private SendOTPRepository sendOTPRepository;

    public void init(Context mContext) {
        sendOTPRepository = SendOTPRepository.getInstance(mContext);
    }

   
    public void setKey() {
        sendOTPRepository.getKey();
    }

    public LiveData<String> getKey() {

        return sendOTPRepository.getLiveData1();
    }
   
}

回购

public class SendOTPRepository {

    private static SendOTPRepository sendOTPRepository;
    private final ApiInterface apiInterface;
   
    MutableLiveData<String> liveData1 = new MutableLiveData<>();

    public SendOTPRepository(Context mContext) {
   
        apiInterface = getClientNew(mContext).create(ApiInterface.class);
    }

    public static SendOTPRepository getInstance(Context mContext) {
        if (sendOTPRepository == null) {
            sendOTPRepository = new SendOTPRepository(mContext);
        }
        return sendOTPRepository;
    }

    public void getKey() {
        Observable<String> call = apiInterface.callAPIURL();
        RXJavaCaller.GetKey(call, new RXJavaCaller.OnKeyReceived() {
            @Override
            public void onKeyReceivedSuccess() {
                LoggerUtils.E("getKey", ApiConstants.KEY_SUCCESS);
                liveData1.setValue(ApiConstants.KEY_SUCCESS);
            }

            @Override
            public void onKeyReceivedError(String error) {
                LoggerUtils.E("getKey", ApiConstants.KEY_ERROR);
                liveData1.setValue(null);
            }
        });

    }

    public MutableLiveData<String> getLiveData1() {
        return liveData1;
    }

}

getLiveData1() 在这我得到空响应

【问题讨论】:

    标签: android mvvm android-livedata mutablelivedata


    【解决方案1】:

    这是正常现象。

    观察者在创建时被触发并返回 null,因为没有加载数据。加载数据后,将再次触发更新。

    要正确处理此问题,请在您的观察者中添加一个空检查:

    sendOTPViewModel.key.observe(viewLifecycleOwner, { key -> {
            if (key != null)
                LoggerUtils.E(TAG, key)
        }})
    

    但是你有没有检查过是不是你这里专门设置了null?

            @Override
            public void onKeyReceivedError(String error) {
                LoggerUtils.E("getKey", ApiConstants.KEY_ERROR);
                liveData1.setValue(null);
            }
    

    【讨论】:

      猜你喜欢
      • 2021-12-08
      • 2023-03-25
      • 2013-07-27
      • 1970-01-01
      • 2019-02-07
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      • 2020-08-08
      相关资源
      最近更新 更多