private lateinit var userDataViewModel: UserDataViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MyApplication.appComponent?.inject(this)
prefs = PreferenceManager.getDefaultSharedPreferences(context)
userDataViewModel = activity?.run {
ViewModelProviders
.of(this, UserDataViewModelFactory(prefs, dataFetcherService))
.get(UserDataViewModel::class.java)
} ?: throw Exception("Invalid Activity")
userDataViewModel.getUserData()
}
TodayFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
prefs = PreferenceManager.getDefaultSharedPreferences(activity)
userDataViewModel = activity?.run {
ViewModelProviders
.of(this, UserDataViewModelFactory(prefs, dataFetcherService))
.get(UserDataViewModel::class.java)
} ?: throw Exception("Invalid Activity")
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
userDataViewModel
.getUserData()
.observe(this, Observer {
clubId = it.club_id // <-- this is where it crashes since 'it' is null
})
}
UserDataViewModel.kt
class UserDataViewModel(
prefs: SharedPreferences,
dataFetcherService: DataFetcherService)
: ViewModel() {
private val useCase = UserDataUseCase(prefs, dataFetcherService)
val userData: MutableLiveData<UserData> by lazy {
MutableLiveData<UserData>().apply { loadUserData() }
}
fun getUserData(): LiveData<UserData> {
return userData
}
private fun loadUserData() {
viewModelScope.launch {
withContext(Dispatchers.IO) {
try {
return@withContext useCase.loadUserData(USER_UNKNOWN)
} catch (t: Throwable) {
return@withContext null
}
}
?.let {
userData.postValue(it)
}
}
}
}
问题出在视图模型中的getUserData()
方法。当我在这些行上设置断点时:
return userData
MutableLiveData<UserData>().apply { loadUserData() }
return@withContext useCase.loadUserData(USER_UNKNOWN)
这些断点都会在LoginFragment中被触发。但是当它进入TodayFragment时,它会在视图模型中的return userData
处触发,然后立即跳回到TodayFragment内部的观察者,并出现一个空指针异常,因为视图模型内的值为空。
我认为这在视图模型本身被实例化的程度上是有道理的,但为什么视图模型内的值为空呢?
出于调试目的,我正在硬编码来自用例和存储库的响应,以确保ViewModel中有一个填充的值。
TodayFragment的屏幕截图(extends AbstractWorkoutFragment)
注意现在mData
为空,但ViewModel是相同的。
UserDataViewModelFactory
? - tynn