DefaultDispatcher-worker-2 while posting value Coroutine - android

My view model looks like this:
class BlogListActivityViewModel #ViewModelInject constructor(
private val blogRepository: BlogRepository,
private val context: Application,
#IoDispatcher private val ioDispatcher: CoroutineDispatcher
) : AndroidViewModel(context) {
var blogDeleteLiveData = MutableLiveData<Resource<DeleteResponse>>()
fun deleteBlog(itemId: Int) {
viewModelScope.launch(ioDispatcher) {
blogDeleteLiveData.postValue(Resource.loading())
try {
val deleteResponse = async { blogRepository.deleteBlog(itemId) }
blogDeleteLiveData.postValue(Resource.success(deleteResponse.await()))
} catch (e: Exception) {
blogDeleteLiveData.postValue(Resource.error(message = context.getString(R.string.unable_to_load_blog)))
}
}
}
}
Calling activity looks like this:
blogListActivityViewModel.blogDeleteLiveData.observe(this, Observer { resource ->
val sweetDialog = SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE)
sweetDialog.titleText = "Deleting"
sweetDialog.setCancelable(false)
resource?.let { resource ->
when (resource.status) {
Resource.Status.SUCCESS -> {
blogListAdapter.deleteBlog(deletedBlog)
sweetDialog.changeAlertType(SweetAlertDialog.SUCCESS_TYPE)
sweetDialog.contentText = "Successfully deleted !!"
sweetDialog.titleText = "Congratulation"
}
Resource.Status.ERROR -> {
sweetDialog.changeAlertType(SweetAlertDialog.ERROR_TYPE)
sweetDialog.contentText = resource.message
sweetDialog.titleText = "Oops Something Wrong"
}
Resource.Status.LOADING -> {
deleteDialog.dismissWithAnimation()
sweetDialog.changeAlertType(SweetAlertDialog.PROGRESS_TYPE)
sweetDialog.contentText = "Please wait while deleting..."
sweetDialog.show()
}
}
}
})
blogListActivityViewModel.deleteBlog(blog.id)
But I m keep getting
FATAL EXCEPTION: DefaultDispatcher-worker-2

Related

android parallel API requests with retrofit and coroutines

I have multiple API requests that need to be called in parallel, the sequence doesn't matter.
What really matters is that all the calls should be requested to implement the UI.
The problem is that sometimes some requests don't get called which returns null values, in other words, NO GUARANTEE THAT ALL THE REQUESTS WILL BE CALLED.
I have read a lot about parallel API requests and launchers but still don't know what I have missed or what I did wrong.
here is my view model class that has all functions
#HiltViewModel
class MatchDetailsViewModel #Inject constructor(
val api:FootballApi,
val app: Application,
): AndroidViewModel(app) {
private val _matchDetailsMutableLiveData = MutableLiveData<ResponseState<FixtureById>>()
private val _matchStatsMutableLiveData = MutableLiveData<ResponseState<Stats>>()
private val _matchLineupsMutableLiveData = MutableLiveData<ResponseState<Lineups>>()
private val _matchBenchMutableLiveData = MutableLiveData<ResponseState<Bench>>()
private val _matchSideLinesMutableLiveData = MutableLiveData<ResponseState<SideLine>>()
private val _matchStandingsMutableLiveData = MutableLiveData<ResponseState<Standings>>()
val matchStandingsLiveData: LiveData<ResponseState<Standings>> = _matchStandingsMutableLiveData
val matchSideLinesLiveData: LiveData<ResponseState<SideLine>> = _matchSideLinesMutableLiveData
val matchStatsLiveData: LiveData<ResponseState<Stats>> = _matchStatsMutableLiveData
val matchDetailsLiveData: LiveData<ResponseState<FixtureById>> = _matchDetailsMutableLiveData
val matchLineupsLiveData: LiveData<ResponseState<Lineups>> = _matchLineupsMutableLiveData
val matchBenchLiveData: LiveData<ResponseState<Bench>> = _matchBenchMutableLiveData
fun callAll() {
viewModelScope.launch {
val getMatchDetailsCall = async { getMatchDetails(1582601) }
val getMatchStatsCall = async { getMatchStats(1582601) }
val getMatchLineupsCall = async { getMatchLineups(1582601) }
val getMatchBenchCall = async { getMatchBench(1582601) }
val getMatchSideLineCall = async { getMatchSideLine(15006543) }
val getMatchStandingsCall = async { getMatchStandings(12880) }
try {
getMatchDetailsCall.await()
getMatchStatsCall.await()
getMatchLineupsCall.await()
getMatchBenchCall.await()
getMatchSideLineCall.await()
getMatchStandingsCall.await()
}
catch (_: Exception){}
}
}
suspend fun getMatchStandings(seasonId: Int) = viewModelScope.launch(Dispatchers.IO) {
_matchStandingsMutableLiveData.postValue(ResponseState.Loading())
try {
val response = api.getMatchStandings(seasonId = seasonId)
Log.i("getMatchStanding()", response.body().toString())
_matchStandingsMutableLiveData.postValue(ResponseState.Success(response.body()!!))
}
catch (exception: Exception) {
Log.e("getMatchStanding()", exception.toString())
}
}
suspend fun getMatchSideLine(id: Int) = viewModelScope.launch(Dispatchers.IO) {
_matchSideLinesMutableLiveData.postValue(ResponseState.Loading())
try {
val response = api.getMatchSideLines(id = id)
Log.i("getMatchSideline()", response.body().toString())
_matchSideLinesMutableLiveData.postValue(ResponseState.Success(response.body()!!))
} catch (exception: Exception) {
Log.e("getMatchSideline()", exception.toString())
}
}
fun getMatchDetails(id: Int) = viewModelScope.launch(Dispatchers.IO) {
_matchDetailsMutableLiveData.postValue(ResponseState.Loading())
try {
val response = api.getMatchDetails(id = id)
Log.i("getMatchDetails()", response.body().toString())
_matchDetailsMutableLiveData.postValue(ResponseState.Success(response.body()!!))
} catch (exception: Exception) {
Log.e("getMatchDetails()", exception.toString())
}
}
suspend fun getMatchStats(id: Int) = viewModelScope.launch(Dispatchers.IO) {
_matchStatsMutableLiveData.postValue(ResponseState.Loading())
try {
val response = api.getMatchStats(id = id)
Log.i("getMatchStats()", response.body().toString())
_matchStatsMutableLiveData.postValue(ResponseState.Success(response.body()!!))
} catch (exception: Exception) {
Log.e("getMatchStats()", exception.toString())
}
}
suspend fun getMatchLineups(id: Int = 6) = viewModelScope.launch(Dispatchers.IO) {
_matchLineupsMutableLiveData.postValue(ResponseState.Loading())
try {
val response = api.getMatchLineups(id = id)
Log.i("getMatchLineups()", response.body().toString())
_matchLineupsMutableLiveData.postValue(ResponseState.Success(response.body()!!))
} catch (exception: Exception) {
Log.e("getMatchLineups()", exception.toString())
}
}
suspend fun getMatchBench(id: Int) = viewModelScope.launch(Dispatchers.IO) {
_matchBenchMutableLiveData.postValue(ResponseState.Loading())
try {
val response = api.getMatchBench(id = id)
Log.i("getMatchBench()", response.body().toString())
_matchBenchMutableLiveData.postValue(ResponseState.Success(response.body()!!))
} catch (exception: Exception) {
Log.e("getMatchBench()", exception.toString())
}
}
}
And here's my call in activity class
lifecycleScope.launch(Dispatchers.IO) {
matchDetailsViewModel.callAll()
}

Live Data Observer called only once _ Android

Live Data Observer called only once. It is not updating the data from server when api is called again to update UI.
Here is my activity:
class LoginActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
onClick(){
callAPI(binding.edtEMail.text.toString(), binding.edtPasswords.text.toString())
}
}
private fun callAPI(userName: String, password: String) {
var factory = object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return LoginViewModel(
networkAvailable,
application,
getLoginUseCase,
userName,
password
) as T
}
}
val loginViewModel: LoginViewModel by lazy {
ViewModelProvider(this, factory)[LoginViewModel::class.java]
}
loginViewModel.loginMainEntity.observe(this, Observer {
when (it) {
is Resource.Success -> {
it.data?.let { it ->
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
}
is Resource.Error -> {
it.message?.let { it ->
when (it) {
getString(R.string.invalid_login) -> {
Toast.makeText(this, R.string.error_user_pass, Toast.LENGTH_LONG)
.show()
}
getString(R.string.service_not_available) -> {
Toast.makeText(
this,
R.string.error_service_not_available,
Toast.LENGTH_LONG
)
.show()
}
else -> {
Toast.makeText(this, it, Toast.LENGTH_LONG)
.show()
}
}
}
}
}
})
}
}
And here is LoginViewModel:
class LoginViewModel constructor
(
private val networkAvailable: NetworkAvailable,
private val app: Application,
private val getLoginUseCase: GetLoginUseCase,
private val userName: String,
private val password: String
) : ViewModel() {
private val _loginMainEntity = MutableLiveData<Resource<LoginMainEntity>>()
val loginMainEntity: LiveData<Resource<LoginMainEntity>>
get() = _loginMainEntity
init {
loginValues()
}
private fun loginValues() {
viewModelScope.launch {
try {
_loginMainEntity.postValue(Resource.Loading())
} catch (e: Exception) {
_loginMainEntity.postValue(Resource.Error(app.resources.getString(R.string.unknown)))
}
try {
if (networkAvailable.isNetworkConnected()) {
try {
_loginMainEntity.postValue(getLoginUseCase.execute(userName, password))
} catch (e: Exception) {
_loginMainEntity.postValue(Resource.Error(app.resources.getString(R.string.error_api)))
}
} else if (!networkAvailable.isNetworkConnected()) {
try {
_loginMainEntity.postValue(Resource.Error(app.resources.getString(R.string.error_api_network)))
} catch (e: Exception) {
_loginMainEntity.postValue(Resource.Error(app.resources.getString(R.string.error_api_network)))
}
}
} catch (e: Exception) {
try {
_loginMainEntity.postValue(Resource.Error(app.resources.getString(R.string.error_api)))
} catch (e: Exception) {
_loginMainEntity.postValue(Resource.Error(app.resources.getString(R.string.error_api)))
}
}
}
}
}

Firebase Auth with Kotlin Flow

I am learning clean architecture and Kotlin Flow. I want to check is user mail exists in the Firebase Auth base. However, when I threw an error to the flow function, app is crash.
CheckUserUseCase.kt
class CheckUserUseCase #Inject constructor(private val repository: SignInRepository) {
operator fun invoke(mail: String): Flow<Status<Boolean, String>> = flow {
emit(Status.Loading(data = null))
try {
repository.isUserExists(mail = mail)
emit(Status.Success(data = true))
} catch (e: Exception) {
emit(Status.Error(message = e.message, data = false))
}
}
}
SignInRepository.kt
interface SignInRepository {
suspend fun isUserExists(mail: String)
}
SignInRepositoryImpl.kt
class SignInRepositoryImpl #Inject constructor(private val firebaseUserActions: FirebaseUserActions) : SignInRepository {
override suspend fun isUserExists(mail: String) {
firebaseUserActions.isUserExists(mail = mail)
}
}
FirebaseAuthentication.kt
class FirebaseAuthentication #Inject constructor(private val auth: FirebaseAuth) : FirebaseUserActions {
override suspend fun isUserExists(mail: String){
auth.fetchSignInMethodsForEmail(mail).addOnCompleteListener { task ->
task.result.signInMethods?.let {
if (it.size != 0) Log.i("App.tag", "True.")
else throw IOException() <-- Crash point.
}
}.addOnFailureListener { e -> e.printStackTrace() }
.await()
}
}
How can I return a state to Kotlin Flow method? Thank you!
Please try the following approach:
override suspend fun isUserExists(mail: String): Status {
return try {
val result = auth.fetchSignInMethodsForEmail(mail).await()
result.signInMethods?.let {
if (it.isNotEmpty()) {
Status.Success(data = true)
} else {
Status.Error(message = "No data", data = false)
}
} ?: Status.Error(message = "No Data", data = false)
} catch (e: Exception) {
Status.Error(message = e.message, data = false)
}
}
In CheckUserUseCase class just emit the result of calling isUserExists():
emit(Status.Loading(data = null))
emit(repository.isUserExists(mail = mail))
Try
it.size != 0 && it.size != null
and
if (task.isSuccessful()) {
[...]
task.result.signInMethods?.let {
[...]
}

How to update RecyclerView when use retrofit?

i want to update RecyclerView when item removed but i dont' have idea to solve, i try to use notifydatasetchanged() but it don't work.
API Interface
interface RetrofitService {
#GET("/")
suspend fun getAllItem() : Response<List<Item>>
#POST("/delete")
suspend fun deleteItem(#Body item :Item) : Response<Item>
class Repository
class ItemRepository(private val retrofitService: RetrofitService) {
suspend fun getAllItem() = retrofitService.getAllItem()
suspend fun deleteItem(item : Item) = retrofitService.deleteItem(item)
}
in ViewModel, i handle result by two function(handleItemResponse and handleListItemResponse)
class ItemViewModel(private val itemRepository: ItemRepository) : ViewModel() {
val itemResponse: MutableLiveData<Resource<Item>> = MutableLiveData()
val listItemResponse : MutableLiveData<Resource<List<Item>>> = MutableLiveData()
fun getItemResponse() = viewModelScope.launch {
val response : Response<List<Item>> = itemRepository.getAllItem()
withContext(Dispatchers.Main) {
listItemResponse.postValue(handleListItemResponse(response))
}
}
fun deleteItem(item: Item) = viewModelScope.launch {
val response = itemRepository.deleteItem(item)
itemResponse.postValue(handleItemResponse(response))
}
private fun handleItemResponse(response: Response<Item>): Resource<Item> {
if (response.isSuccessful) {
response.body()?.let { resultResponse ->
return Resource.Success(resultResponse)
}
}
return Resource.Error(response.message())
}
private fun handleListItemResponse(response: Response<List<Item>>): Resource<List<Item>> {
if (response.isSuccessful) {
response.body()?.let { resultResponse ->
return Resource.Success(resultResponse)
}
}
return Resource.Error(response.message())
}
}
and class Resource to logging result
sealed class Resource<T>(
val data:T?=null,
val messaage : String? = null
) {
class Success<T>(data:T) : Resource<T>(data)
class Error<T>(messaage: String,data:T? = null) : Resource<T>(data,messaage)
class Loading<T> : Resource<T>()
}
in Fragment , i use ViewModel like this
viewModel.listItemResponse.observe(viewLifecycleOwner, Observer {
when (it) {
is Resource.Success -> {
Toast.makeText(context,"All Success",Toast.LENGTH_SHORT).show()
it.data?.let { itemReponse ->
listItem = itemReponse
adapter.setNotes(listItem)
}
}
is Resource.Error -> {
it.messaage?.let { msg ->
Log.e("AAA","ERR:$msg ")
}
}
}
})
viewModel.getItemResponse()
}
in Adapter , i getList by function setNotes
fun setNotes(items:List<Item>){
this.items = items
notifyDataSetChanged()
}
and function to delete item
private val onItemDelete:(Item)->Unit ={ item ->
viewModel.itemResponse.observe(viewLifecycleOwner, Observer {
when (it) {
is Resource.Success -> {
it.data?.let {
Toast.makeText(context,"Delete successfully!",Toast.LENGTH_SHORT).show()
}
}
is Resource.Error -> {
it.messaage?.let { msg ->
Toast.makeText(context," \"ERR:$msg \"",Toast.LENGTH_SHORT).show()
}
}
}
})
viewModel.deleteItem(item)
}
My english not well , so i hope you sympathize and help me, have a nice day,everyone!
I fixed it, i put it for anyone face same my problem.
private val onItemDelete:(Int)->Unit ={ pos ->
viewModel.itemResponse.observe(viewLifecycleOwner, Observer {
when (it) {
is Resource.Success -> {
it.data?.let {
listItem.removeAt(pos)
adapter.notifyItemRemoved(pos)
}
}
is Resource.Error -> {
it.messaage?.let { msg ->
Toast.makeText(context," \"ERR:$msg \"",Toast.LENGTH_SHORT).show()
}
}
}
})
viewModel.deleteItem(listItem[pos])
}
just callback position of item then get it in fragment.

Make android MVVM, Kotlin Coroutines and Retrofit 2.6 work asynchronously

I've just finished my first Android App. It works as it should but, as you can imagine, there's a lot of spaghetti code and lack of performance. From what I've learned on Android and Kotlin language making this project (and a lot of articles/tutorials/SO answers) I'm trying to start it again from scratch to realize a better version. For now I'd like to keep it as simple as possible, just to better understand how to handle API calls with Retrofit and MVVM pattern, so no Volley/RXjava/Dagger etc.
I'm starting from the login obviously; I would like to make a post request to simply compare the credentials, wait for the response and, if positive, show a "loading screen" while fetching and processing data to show in the home page. I'm not storing any information so I have realized a singleton class that holds data as long as the app is running (btw, is there another way to do it?).
RetrofitService
private val retrofitService = Retrofit.Builder()
.addConverterFactory(
GsonConverterFactory
.create(
GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.setLenient().setDateFormat("yyyy-MM-dd")
.create()
)
)
.addConverterFactory(RetrofitConverter.create())
.baseUrl(BASE_URL)
.build()
`object ApiObject {
val retrofitService: ApiInterface by lazy {
retrofitBuilder.create(ApiInterface::class.java) }
}
ApiInterface
interface ApiInterface {
#GET("workstation/{date}")
suspend fun getWorkstations(
#Path("date") date: Date
): List<Workstation>
#GET("reservation/{date}")
suspend fun getReservations(
#Path("date") date: Date
): List<Reservation>
#GET("user")
suspend fun getUsers(): List<User>
#GET("user/login")
suspend fun validateLoginCredentials(
#Query("username") username: String,
#Query("password") password: String
): Response<User>
ApiResponse
sealed class ApiResponse<T> {
companion object {
fun <T> create(response: Response<T>): ApiResponse<T> {
return if(response.isSuccessful) {
val body = response.body()
// Empty body
if (body == null || response.code() == 204) {
ApiSuccessEmptyResponse()
} else {
ApiSuccessResponse(body)
}
} else {
val msg = response.errorBody()?.string()
val errorMessage = if(msg.isNullOrEmpty()) {
response.message()
} else {
msg.let {
return#let JSONObject(it).getString("message")
}
}
ApiErrorResponse(errorMessage ?: "Unknown error")
}
}
}
}
class ApiSuccessResponse<T>(val data: T): ApiResponse<T>()
class ApiSuccessEmptyResponse<T>: ApiResponse<T>()
class ApiErrorResponse<T>(val errorMessage: String): ApiResponse<T>()
Repository
class Repository {
companion object {
private var instance: Repository? = null
fun getInstance(): Repository {
if (instance == null)
instance = Repository()
return instance!!
}
}
private var singletonClass = SingletonClass.getInstance()
suspend fun validateLoginCredentials(username: String, password: String) {
withContext(Dispatchers.IO) {
val result: Response<User>?
try {
result = ApiObject.retrofitService.validateLoginCredentials(username, password)
when (val response = ApiResponse.create(result)) {
is ApiSuccessResponse -> {
singletonClass.loggedUser = response.data
}
is ApiSuccessEmptyResponse -> throw Exception("Something went wrong")
is ApiErrorResponse -> throw Exception(response.errorMessage)
}
} catch (error: Exception) {
throw error
}
}
}
suspend fun getWorkstationsListFromService(date: Date) {
withContext(Dispatchers.IO) {
val workstationsListResult: List<Workstation>
try {
workstationsListResult = ApiObject.retrofitService.getWorkstations(date)
singletonClass.rWorkstationsList.postValue(workstationsListResult)
} catch (error: Exception) {
throw error
}
}
}
suspend fun getReservationsListFromService(date: Date) {
withContext(Dispatchers.IO) {
val reservationsListResult: List<Reservation>
try {
reservationsListResult = ApiObject.retrofitService.getReservations(date)
singletonClass.rReservationsList.postValue(reservationsListResult)
} catch (error: Exception) {
throw error
}
}
}
suspend fun getUsersListFromService() {
withContext(Dispatchers.IO) {
val usersListResult: List<User>
try {
usersListResult = ApiObject.retrofitService.getUsers()
singletonClass.rUsersList.postValue(usersListResult.let { usersList ->
usersList.filterNot { user -> user.username == "admin" }
.sortedWith(Comparator { x, y -> x.surname.compareTo(y.surname) })
})
} catch (error: Exception) {
throw error
}
}
}
SingletonClass
const val FAILED = 0
const val COMPLETED = 1
const val RUNNING = 2
class SingletonClass private constructor() {
companion object {
private var instance: SingletonClass? = null
fun getInstance(): SingletonClass {
if (instance == null)
instance = SingletonClass()
return instance!!
}
}
//User
var loggedUser: User? = null
//Workstations List
val rWorkstationsList = MutableLiveData<List<Workstation>>()
//Reservations List
val rReservationsList = MutableLiveData<List<Reservation>>()
//Users List
val rUsersList = MutableLiveData<List<User>>()
}
ViewModel
class ViewModel : ViewModel() {
private val singletonClass = SingletonClass.getInstance()
private val repository = Repository.getInstance()
//MutableLiveData
//Login
private val _loadingStatus = MutableLiveData<Boolean>()
val loadingStatus: LiveData<Boolean>
get() = _loadingStatus
private val _successfulAuthenticationStatus = MutableLiveData<Boolean>()
val successfulAuthenticationStatus: LiveData<Boolean>
get() = _successfulAuthenticationStatus
//Data fetch
private val _listsLoadingStatus = MutableLiveData<Int>()
val listsLoadingStatus: LiveData<Int>
get() = _listsLoadingStatus
private val _errorMessage = MutableLiveData<String>()
val errorMessage: LiveData<String>
get() = _errorMessage
fun onLoginClicked(username: String, password: String) {
launchLoginAuthentication {
repository.validateLoginCredentials(username, password)
}
}
private fun launchLoginAuthentication(block: suspend () -> Unit): Job {
return viewModelScope.launch {
try {
_loadingStatus.value = true
block()
} catch (error: Exception) {
_errorMessage.postValue(error.message)
} finally {
_loadingStatus.value = false
if (singletonClass.loggedUser != null)
_successfulAuthenticationStatus.value = true
}
}
}
fun onLoginPerformed() {
val date = Calendar.getInstance().time
launchListsFetch {
//how to start these all at the same time? Then wait until their competion
//and call the two methods below?
repository.getReservationsListFromService(date)
repository.getWorkstationsListFromService(date)
repository.getUsersListFromService()
}
}
private fun launchListsFetch(block: suspend () -> Unit): Job {
return viewModelScope.async {
try {
_listsLoadingStatus.value = RUNNING
block()
} catch (error: Exception) {
_listsLoadingStatus.value = FAILED
_errorMessage.postValue(error.message)
} finally {
//I'd like to perform these operations at the same time
prepareWorkstationsList()
prepareReservationsList()
//and, when both completed, set this value
_listsLoadingStatus.value = COMPLETED
}
}
}
fun onToastShown() {
_errorMessage.value = null
}
}
LoginActivity
class LoginActivity : AppCompatActivity() {
private val viewModel: LoginViewModel
get() = ViewModelProviders.of(this).get(LoginViewModel::class.java)
private val loadingFragment = LoadingDialogFragment()
var username = ""
var password = ""
private lateinit var loginButton: Button
lateinit var context: Context
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
loginButton = findViewById(R.id.login_button)
loginButton.setOnClickListener {
username = login_username.text.toString().trim()
password = login_password.text.toString().trim()
viewModel.onLoginClicked(username, password.toMD5())
}
viewModel.loadingStatus.observe(this, Observer { value ->
value?.let { show ->
progress_bar_login.visibility = if (show) View.VISIBLE else View.GONE
}
})
viewModel.successfulAuthenticationStatus.observe(this, Observer { successfullyLogged ->
successfullyLogged?.let {
loadingFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.CustomLoadingDialogFragment)
if (successfullyLogged) {
loadingFragment.show(supportFragmentManager, "loadingFragment")
viewModel.onLoginPerformed()
} else {
login_password.text.clear()
login_password.isFocused
password = ""
}
}
})
viewModel.listsLoadingStatus.observe(this, Observer { loadingResult ->
loadingResult?.let {
when (loadingResult) {
COMPLETED -> {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
setResult(Activity.RESULT_OK)
finish()
}
FAILED -> {
loadingFragment.changeText("Error")
loadingFragment.showProgressBar(false)
loadingFragment.showRetryButton(true)
}
}
}
})
viewModel.errorMessage.observe(this, Observer { value ->
value?.let { message ->
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
viewModel.onToastShown()
}
})
}
Basically what I'm trying to do is to send username and password, show a progress bar while waiting for the result (if successful the logged user object is returned, otherwise a toast with the error message is shown), hide the progress bar and show the loading fragment. While showing the loading fragment start 3 async network calls and wait for their completion; when the third call is completed start the methods to elaborate the data and, when both done, start the next activity.
It seems to all works just fine, but debugging I've noticed the flow (basically network calls start/wait/onCompletion) is not at all like what I've described above. There's something to fix in the ViewModel, I guess, but I can't figure out what

Categories

Resources