0

I've got the following ViewModel:

class FundamentalsViewModel: ViewModel() {
    var fundamentalsLiveData = MutableLiveData<WrappedResult<DataResponse>>()
    private val repository = FundamentalsRespository()
    private var job: Job? = null

    fun getData(type: String) {
        if(job == null || job?.isActive == false) {
            fundamentalsLiveData.value = WrappedResult.Loading
            job = viewModelScope.launch(Dispatchers.IO) {
                try {
                    val response = repository.getData(type)
                    withContext(Dispatchers.Main) {
                        fundamentalsLiveData.value = WrappedResult.Success(response)
                    }
                } catch(e: Exception) {
                    withContext(Dispatchers.Main) {
                        fundamentalsLiveData.value = WrappedResult.Failure(e)
                    }
                }
            }
        }
    }
}

Everything works perfectly in-house, but out in the field I'm getting Crashylitics reports that say this: "Fatal Exception: java.lang.NullPointerException Parameter specified as non-null is null: method kotlin.j0.d.u.p, parameter symbol" on the line that is:

fundamentalsLiveData.value = WrappedResult.Loading

There is no other information in the crash log. How is it possible that there is any NPE here? The WrappedResult is a typical Kotlin sealed class that looks like this:

sealed class WrappedResult<out T> {
    data class Success<out T: Any>(val data:T) : WrappedResult<T>()
    data class Failure(val error: Throwable) : WrappedResult<Nothing>()
    data class CallFailure(val error: String) : WrappedResult<Nothing>()
    object Loading : WrappedResult<Nothing>()
}
3
  • Could it be a problem of declaration/init for object Loading in WrappedResult? Commented Sep 16, 2020 at 11:22
  • I considered that, however if that's the case I don't know how to fix the problem. Also, I've test just explicitly setting fundamentalsLiveData.value = null and I don't get a crash. Commented Sep 16, 2020 at 13:15
  • I think that this would only suggest that the problem really regards the Loading object, i've never programmed in Kotlin, just wondering around. But i think that's the problem here. Commented Sep 16, 2020 at 13:28

1 Answer 1

0

I found the issue and it had to do with the fragment having setRetainInstance(false). If the activity was killed on a task out, this happened coming back in. I haven't yet been able to fully understand how why this would happen since the view model was created with the fragment's scope, but changing to setRetainInstance(true) stopped the crash.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.