I have following Espresso test :
#Test
fun testSearchItemFound() {
onView(withId(R.id.action_search)).perform(click())
onView(isAssignableFrom(EditText::class.java))
.perform(typeText("Harry Potter"),
pressImeActionButton())
// Check error message view is not displayed
onView(withId(R.id.error_msg)).check(matches(not<View>(isDisplayed())))
// Check the item we are looking for is in the search result list.
onData(allOf(`is`<Any>(instanceOf<Any>(String::class.java)),
withItemContent("Harry Potter")))
.check(matches(isDisplayed()))
}
The first line of code :
onView(withId(R.id.action_search)).perform(click())
will be executed properly when EspressoIdlingResource is idle.
But last line of code:
onData(allOf(`is`<Any>(instanceOf<Any>(String::class.java)),
withItemContent("Harry Potter")))
.check(matches(isDisplayed()))
Will be executed when we have following code in MainFragment:
// The network request might be handled in a different thread so make sure Espresso knows
// that the app is busy until the response is handled.
EspressoIdlingResource.increment() // App is busy until further notice
model.movies.observe(this#MainFragment, Observer<PagedList<Movie>> {
// This callback may be called twice, once for the cache and once for loading
// the data from the server API, so we check before decrementing, otherwise
// it throws "Counter has been corrupted!" exception.
if (!EspressoIdlingResource.getIdlingResource().isIdleNow) {
EspressoIdlingResource.decrement() // Set app as idle.
}
adapter.submitList(it)
})
If I disable :
EspressoIdlingResource.increment() // App is busy until further notice
And :
if (!EspressoIdlingResource.getIdlingResource().isIdleNow) {
EspressoIdlingResource.decrement() // Set app as idle.
}
First line works properly :
onView(withId(R.id.action_search)).perform(click())
Is there any solution to handle this exceptional case?
Source can be found at : https://github.com/Ali-Rezaei/TMDb-Paging/tree/master/app/src/androidTest/java/com/sample/android/tmdb
Related
I have been facing this issue for quite sometime and would like to know a better approach to solve this problem. If you are aware of anything about how to solve it then please let me know.
I am building a project which takes data from an API and then following MVVM architecture I take the Retrofit instance to Repository, and then to ViewModel and further observe it from my fragment.
Now what I am working on currently is Login feature. I will send a number to the API and in response I will receive if the number is registered or not. If it is registered then I would move to the next screen.
Now the problem is that using one of the function in ViewModel I send that number to the API to get the response. And using a variable I observe that response.
Now I create a function which checks if the response was true or false and based on that I am using the logic to move to the next screen, but the issue is the returned value from the function. As LiveData works asynchronously in background it takes some time to return the value and in meantime the function returns the initial value which is false.
Function to verify response
private fun checkNumber(): Boolean {
var valid = false
authRiderViewModel.response.observe(viewLifecycleOwner, Observer {
Timber.d("Response: $it")
if (it.success == true) {
valid = true
}
})
Timber.d("Boolean: $valid")
return valid
}
Moving to next screen code:
binding.btnContinue.setOnClickListener {
val number = binding.etMobileNumber.text.toString().toLong()
Timber.d("Number: $number")
authRiderViewModel.authDriver(number)
if (checkNumber()) {
val action = LoginFragmentDirections.actionLoginFragmentToOtpFragment()
findNavController().navigate(action)
} else {
Toast.makeText(requireContext(), "Number not registered", Toast.LENGTH_SHORT).show()
}
}
So in case I received the true response from the server even then I would not move to the next screen because the initial value I received is false. I have spent few hours trying to fix it and any help would be appreciated. If you need any code let me know in comments. Thanks.
You have four distinct states:
The server returned a positive response
The server returned a negative response
The server failed (e.g., returned a 500, timed out)
You are waiting on the server
You are attempting to model that with two states: true and false. This will not work.
Instead, model it with four states. One approach is called "loading-content-error" and uses a sealed class to represent those states:
sealed class LoginState {
object Loading : LoginState()
data class Content(val isSuccess: Boolean) : LoginState()
object Error : LoginState()
}
Your LiveData (or your StateFlow, once you migrate to coroutines) would be a LiveData<LoginState>. Your observer can then use a when to handle Loading, Content, and Error as needed, such as:
For Loading, display a progress indicator
For Content, do whatever you are doing now with your boolean
For Error, display an error message
Actually, live data observation is an asynchronous operation. You have to code accordingly.
Just calling checkNumber() won't return since is asynchronous instead I give you some ideas to implement in a better way.
Just call the checkNumber when button click inside the check number do this instead of return valid
authRiderViewModel.response.observe(viewLifecycleOwner, Observer {
Timber.d("Response: $it")
if (it.success == true) {
val action = LoginFragmentDirections.actionLoginFragmentToOtpFragment()
findNavController().navigate(action)
} else {
Toast.makeText(requireContext(), "Number not registered", Toast.LENGTH_SHORT).show()
}
})
I was looking at the flow documentation on the Android Developer site and I have a question.
https://developer.android.com/kotlin/flow#callback
If you look at the above link, you will see code like this.
class FirestoreUserEventsDataSource(
private val firestore: FirebaseFirestore
) {
// Method to get user events from the Firestore database
fun getUserEvents(): Flow<UserEvents> = callbackFlow {
// Reference to use in Firestore
var eventsCollection: CollectionReference? = null
try {
eventsCollection = FirebaseFirestore.getInstance()
.collection("collection")
.document("app")
} catch (e: Throwable) {
// If Firebase cannot be initialized, close the stream of data
// flow consumers will stop collecting and the coroutine will resume
close(e)
}
// Registers callback to firestore, which will be called on new events
val subscription = eventsCollection?.addSnapshotListener { snapshot, _ ->
if (snapshot == null) { return#addSnapshotListener }
// Sends events to the flow! Consumers will get the new events
try {
offer(snapshot.getEvents())
} catch (e: Throwable) {
// Event couldn't be sent to the flow
}
}
// The callback inside awaitClose will be executed when the flow is
// either closed or cancelled.
// In this case, remove the callback from Firestore
awaitClose { subscription?.remove() }
}
}
In the code above, awaitClose is explained to be executed when the coroutine is closed or cancelled.
But, there is no close() in the code except for the try-catch statement that initializes the eventsCollection.
Additionally, says offer does not add the element to the channel and **returns false** immediately at the bottom of the Android Developer page.
My question is, in the code above, when offer(snapshot.getEvents()) is executed, does the coroutine cancel with return false, so awaitClose is executed?
Expectation:
As the documentation says:
When you try to add a new element to a full channel, send suspends the
producer until there's space for the new element, whereas offer does
not add the element to the channel and returns false immediately.
Ergo:
It Immediately adds the specified element to this channel, if this doesn’t violate its capacity restrictions, and returns the successful result. Otherwise, returns failed or closed result. This is synchronous variant of send, which backs off in situations when send suspends or throws.
So when trySend call returns a non-successful result, it guarantees that the element was not delivered to the consumer, and it does not call onUndeliveredElement that was installed for this channel. See “Undelivered elements” section in Channel documentation for details on handling undelivered elements.
Conclusion:
A typical usage for onDeliveredElement is to close a resource that is being transferred via the channel. The following code pattern guarantees that opened resources are closed even if producer, consumer, and/or channel are cancelled. Resources are never lost. So no it doesn't return false.
I am writing a toy Android app using Kotlin flow and Android Paging 3 library. The app calls some remote API to get a list of photos, and display them using a RecyclerView with a PagingDataAdapter.
I find that the code after pagingAdapter.submitData() is not executed.
Here is the code snippet (this function is in a Fragment):
fun refreshList() {
lifecycleScope.launch {
photosViewModel.listPhotos().collect {
// `it` is PagingData<Photo>
pagingAdapter.submitData(it)
Log.e(TAG, "After submitData")
}
}
}
The log After submitData is not printed.
However, if I put the logging in front of the pagingAdapter.submitData() line, it is printed, like this:
fun refreshList() {
lifecycleScope.launch {
photosViewModel.listPhotos().collect {
// `it` is PagingData<Photo>
Log.e(TAG, "Before submitData")
pagingAdapter.submitData(it)
}
}
}
The log Before submitData is printed with no problem.
Why does this happen, please?
.submitData is a suspending function which does not return until invalidation or refresh. As long as Paging is actively loading (collecting) from the PagingData you provided, it will not finish. This is why it must be done in a launched job.
For the same reason, make sure to use collectLatest instead of collect to make sure you cancel and start displaying new generations as soon as possible.
So what I want to do is get data from the API and depending on the result change the status so the observer of the status gets notified and can act accordingly.
fun getQuestionsByRelatedCategoriesFromApi(categoryId: Int, language: String){
faqFetchStatus.onNext(NetworkStatus.STARTED)
faqService.getQuestionsOfCategory(categoryId, language)
.subscribeOn(Schedulers.io())
.subscribe(
{
Log.d("FaqRepository", "Fetching ${it.size} questions from API")
//adding the language to the question for DB calls
for (element in it) {
element.language = language
}
insertQuestionsInDb(it)
faqFetchStatus.onNext(NetworkStatus.FINISHED)
},
{
faqFetchStatus.onNext(NetworkStatus.FAILED)
}
)
}
The View calls the ViewModel which in return calls the above function in the Repository. As expected the status gets changed to "STARTED" and a loading circle is shown. However the subscribe code never gets called which results in an infinite loading loop (form users perspective).
If I remove subscribeOn(Schedulers.io()) the code in subscribe() gets executed but since it's now a call on the main Thread I recieve the following error.
android.os.NetworkOnMainThreadException
What am I doing wrong here?
I am trying to implement a refresh token flow in RxJava2 and Kotlin and I have trouble handling errors. There are several requests that need to be done in sequence but the sequence differs in case there are some errors.
Basically, if I try to use my refresh token and receive 400 - Bad Requestresponse because the token is not valid, I need to terminate the flow and do not execute the next switchMap (and ideally, I would like to return the final Observable<ApplicationRoot>). But I am not sure how to achieve this.
If I use onErrorReturn, I will just pass the returned result to the next switch map. And doOnError just executes the step when the request fails but the whole sequence continues.
fun refreshToken(): Observable<ApplicationRoot> {
// try to use the refresh token to obtain an access token
return authRepository.refreshToken(token)
.switchMap { response ->
// process response here
userRepository.getUser() // fetch user details
}.doOnError {
// TODO - return final result, do not jump to next switchMap
// refresh token is not valid -> go to login screen
Observable.just(ApplicationRoot.LOGIN) // not working
}.switchMap { response -> // excpects response of type UserResponse
// save user details here
}
}
Does anyone know who to jump out of the sequence of switch maps if some error occurs?
Probably, you should do something like this:
fun refreshToken(): Observable<ApplicationRoot> {
return authRepository.refreshToken(token)
.switchMap { response ->
userRepository.getUser()
}
.switchMap { response -> // do something with user response
}
.map { ApplicationRoot.ROOT_THAT_MEANS_SUCCESS }
.onErrorResumeNext(Observable.just(ApplicationRoot.LOGIN))
}
I am not aware about implementation of authRepository.refreshToken and how do responses look like, but in case if response is your custom object rather than retrofit2.Response<T> it should work.