Home > Net >  When I use livedata {}, how do I handle the application crash caused by network timeout?
When I use livedata {}, how do I handle the application crash caused by network timeout?

Time:10-21

viewmodel:

fun getAuthenticationBrieInfo() = liveData {
 emit(authenticationRepository.getAuthenticationBrieInfo())
}

fragment:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
 super.onViewCreated(view, savedInstanceState)
 authenticationViewModel.getAuthenticationBrieInfo().observe(viewLifecycleOwner) {

 }
}

When I don't have a network, it will crash. What should I do? I want to handle the crash and return the prompt message of "no network" to the user.

CodePudding user response:

Simply check the user device for network and if you detect the user is connected to a network, then you can execute the code you provided.

If the issue is with you not getting data from your repository and getting a null pointer exception then simply check for null data. I think the way you have setup to call function inside your live data is a bit concerning which is causing app to crash on network error. You can format your code some other way. I will be able to help with that if you provide more code or information on what you are trying to do.

CodePudding user response:

I'm a novice on Android. I'm using retrofit2 to make network requests, and then use livedata to send data from the viewmodel to the fragment. Now everything seems normal, but when there is no network, the program will crash. I don't know what to do. The following is a request example, which will request api data and display it to the UI. fragment:

userViewModel.getStudyProgressByRemote(). observe(this) { 
     setProgressInfo(it)
}

videomodel:

@HiltViewModel
open class UserViewModel @Inject constructor(
  private val userRepository: UserRepository
 ) : ViewModel() {
    fun getStudyProgressByRemote() = liveData {
       emit(userRepository.getStudyProgress())
    }
 }

repository:

class UserRepository @Inject constructor(var userService: UserService) {
    suspend fun getStudyProgress(): StudyProgress?  {
      return userService.getStudyProgress().data
    }
 }

service:

interface UserService {
    @GET("user/getStudyProgress")
    suspend fun getStudyProgress(): Response<StudyProgress?>
}

class Response<T> {
    var code: Int = 200
    var msg: String = ""
    var data: T? = null
}

In addition, there are some injection codes using hilt, which I omit here.

  • Related