0

我在不执行 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()在这我得到空响应

4

1 回答 1

0

这是正常行为。

观察者在创建时被触发并将返回 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);
        }
于 2020-11-19T22:20:25.873 回答