One of my first android tutorials in my life was one of your videos. The one where you show how to implement an OnClick method for a Button and here I am again, after almost 4 years and 2 jobs as an Android developer, learning how to use Coroutines. Thanks Mitch
10:28 That's why you should never use tight timeouts. A time out should be of a length that can not be reached when executed correctly. Using a tight timeout makes stuff time out that was executed correctly but under suboptimal circumstances. That's usually not your goal.
Funny thing, Retrofit supports timeout exceptions so you can actually set a writeTime and it should throw the exception where you need it. But for some unknown reasons, the timeouts never worked for me where they should. What makes it even more sinister is the fact that the timeout exception gets thrown every time I use debugger or profiler, but never actually when I am just running the app. It keeps loading forever. So I did a trick, just like you, with coroutines and delay. I created an extension function where you pass the right context for the scopes (lifecycleScope for activity and viewModelScope for viewModel) and handled my scenarios there. And then I execute the task, if it completes faster than the timeout/delay, I destroy the job with the delay and start the next activity, otherwise I wait for the delay and display a retry button after 14 seconds in case of failure. Kotlin rocks!
how we can manage different jobs like I've a recycler that contains button in each row with state of invite . when I click on button I have an another state that is undo state for that invite .how to undo request within 10 second .?
Firstly thanks for such a great video . Now , 1 question . While I was trying the above example , I created 2 jobs with via launch() and other via withTimeoutOrNull() , within same single scope inside method fakeApiRequest() AND increased the delay time inside getResult*FromApi() to 3 second each and JOB_TIMEOUT to 4000L . Now when I execute , I see the 2 different jobs running in parallel . And in video u said the 2nd job will execute after the completion of first job . Can you please help me in understanding my concern. One thing more if you change the order of job , say if you call launch() before withTimeoutOrNull() , we see parallel execution BUT if we call withTimeoutOrNull() before launch() , we see sequential execution !!
bro is there a way to run a task in Coroutines for 5 sec intervals indefinitely. cancelled only when i call cancel function. currently im doing this with Handler and its post delayed method with a runnable
@@codingwithmitch what i mean is about setting the timeout in OKHTTP instead of setting it in coroutines. which is better? anyways thank you so much to all of your video tutorials. it means a lot for me =)
This is nice and beautiful, looking forward to your new course. Quick question: is the new project using Paging lib from jetpack? I'd love to see using that :)
I'm confused, why doesn't Coroutine provide an event listener, I've been browsing about it, all of them are custom listeners, any body here has the same problem?
There is a listener. But it's experimental right now: kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/invoke-on-completion.html. I show you how to use it in my powerful android apps with jetpack architecture course: codingwithmitch.com/courses/powerful-android-apps-with-jetpack-architecture/
I am not familiar with Kotlin coroutines as yet, but I suspect that the delay() function only guarantees a minimum delay of that number of milliseconds (the docs say it depends on the dispatcher as to how it is timed). Your first run probably amounted to just over 2100ms because the delays were longer than 1000ms.
It'll be a big one. The app is much larger than the other courses I've made. Its hard to say when I'll begin publishing lectures. I'm still designing the app.
The thing is that when using Retrofit for example you don't have to implement a withTimeoutOrNull. That's because the timeout is configured in the library. So perhaps the next video should be (just suggesting) on handling errors in Coroutines (which one of them is SOCKETTIMEOUTEXCEPTION)
@@codingwithmitch Not really if you use an interceptor. Don't know if you are refering to the same case: .connectTimeout(100, TimeUnit.SECONDS) .readTimeout(100, TimeUnit.SECONDS) which after build() returns the OkHttpClient.
@@coroutinedispatcher yes I know what you're talking about. It's not ideal to use in something like a NetworkBoundResource class as recommended with mvvm architecture in google sample github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/repository/NetworkBoundResource.kt . At least I've tried and it was not easy to handle the logic. If you have an example I'd love to see. Having a coroutine job pattern with a timeout fits in very nicely.
Hi Mitch, Can you make video on "Koin" library usage, it's option for Dagger in Kotlin. It would be great if you do so. Thanks for videos really helpful. Happy coding.
Awesome , thanks for this series of tutorial. I have a question. I want to get request to network every 3 seconds and in the some condition stop it. I use coroutines for network request. Except post handler, Is there another way to do this work ?
You could just do a while loop with a 3 second delay inside. Then if some condition cancel the job. while(conditionIsTrue){ launch{ networkMethod() delay(3000) } }
@@codingwithmitch I try your solution. But The UI have freezed. I create network request in the this repository : class ProcessRepository @Inject constructor(private val apiService: ApiService) { val _networkState = MutableLiveData() val _networkState_first = MutableLiveData() val completableJob = Job() private val coroutineScope = CoroutineScope(Dispatchers.IO + completableJob) private val brokerProcessResponse = MutableLiveData() fun repeatRequest(processId:String):MutableLiveData{ var networkState = NetworkState(Status.LOADING, userMessage) _networkState.postValue(networkState) coroutineScope.launch { val request = apiService.repeatRequest(processId, token) withContext(Dispatchers.Main) { try { val response = request.await() if (response.isSuccessful) { brokerProcessResponse.postValue(response.body()) var networkState = NetworkState(Status.SUCCESS, userMessage) _networkState.postValue(networkState) } else { var networkState = NetworkState(Status.ERROR, userMessage) _networkState.postValue(networkState) } } catch (e: IOException) { var networkState = NetworkState(Status.ERROR, userMessage) _networkState.postValue(networkState) } catch (e: Throwable) { var networkState = NetworkState(Status.ERROR, userMessage) _networkState.postValue(networkState) } } delay(3000) } return brokerProcessResponse } And this is code in my fragment: private fun repeatRequest(){ viewModel.repeatRequest(processId).observe(this, Observer { if(it!=null){ process=it.process if(it.process.state== FINDING_BROKER || it.process.state==NONE){ inProgress(true) }else{ inProgress(false) } setState(it!!.process.state!!,it.process) } }) } private fun pullRequest(){ while (isPullRequest){ repeatRequest() } }
"if this is helpful", seriously?
This is surely very helpful. Thanks for the video.
One of my first android tutorials in my life was one of your videos. The one where you show how to implement an OnClick method for a Button and here I am again, after almost 4 years and 2 jobs as an Android developer, learning how to use Coroutines. Thanks Mitch
coroutines is just perfect. it will replace a lot of inconvenient stuff.
thx for the series.
10:28
That's why you should never use tight timeouts.
A time out should be of a length that can not be reached when executed correctly.
Using a tight timeout makes stuff time out that was executed correctly but under suboptimal circumstances.
That's usually not your goal.
Thanks so much for the great content. I'm moving my Java project to Kotlin after seeing how much better these Kotlin coroutines are than AsyncTasks 🤢
Thanks man for making these series 👍
Best video by you for all the new stuff in Android
Keep Going Good bro, thanks
These videos are remarkably good. You're really good.
Awesome and thanks for the great content .
Very usefull, excellent video regards from Caracas, Venezuela
Another very useful tutorial. Very well put together and explained. Keep up the good work.
Funny thing, Retrofit supports timeout exceptions so you can actually set a writeTime and it should throw the exception where you need it. But for some unknown reasons, the timeouts never worked for me where they should. What makes it even more sinister is the fact that the timeout exception gets thrown every time I use debugger or profiler, but never actually when I am just running the app. It keeps loading forever. So I did a trick, just like you, with coroutines and delay. I created an extension function where you pass the right context for the scopes (lifecycleScope for activity and viewModelScope for viewModel) and handled my scenarios there. And then I execute the task, if it completes faster than the timeout/delay, I destroy the job with the delay and start the next activity, otherwise I wait for the delay and display a retry button after 14 seconds in case of failure. Kotlin rocks!
Yeah I do something similar but in the repository. I had the same experiences with Retrofit timeouts. They didn't work as expected.
Wow..Kotlin owes u buddy...thanks a lot fr this series...
Your tutorial videos are sooooooo useful. Thanks man!
Awesome, I hope I can get more videos about coroutine
Love your content and the way you explain.
Are coroutines analogous to contextualized JavaScript Promises?
how we can manage different jobs like I've a recycler that contains button in each row with state of invite . when I click on button I have an another state that is undo state for that invite .how to undo request within 10 second .?
likes it, loves it. wants more.
why suspend funs?
Are they used only to restrict a fun not to be used outside coroutine scope or other suspend functions ?
Calm and essential. Super!
Is there a video about retry with Coroutines?
If a suspend function suspends and resumes , how does it runs sequentially in the launch coroutine scope?
Cool.. 👍
Make more videos on Coroutines.
Very helpful!! Thank you very Mitch.
You saved my life!!!!
Great stuff!!! And also, you look like G-Eazy in the thumbnail of this video
Can understand withTimeout Vs withTimeoutOrNull
And Love You Sir
Very helpful Sir. Please also add a full fledged course based on MVVM, Coroutines, Dagger and Unit Testing.
Great stuff thanks. Look forward to async/await and more on coroutines 👍
@CodingWithMitch Please make more videos.
Very good video
I really like the way u explain..
Thanks. I like the way you comment.
Why does the job get launched in withContext(IO) scope? Why not use CoroutineScope(IO){...} in line 30?
And you used CoroutineScope(IO){...} in fakeApiRequest() in Async+Await video, which is different from these code
excellent videos ! Thanks! :D I will pay for your courses
Best money you'll ever spend
Love your videos bro
Hi, why you dont use ".await"?
Firstly thanks for such a great video .
Now , 1 question . While I was trying the above example , I created 2 jobs with via launch() and other via withTimeoutOrNull() , within same single scope inside method fakeApiRequest() AND increased the delay time inside getResult*FromApi() to 3 second each and JOB_TIMEOUT to 4000L . Now when I execute , I see the 2 different jobs running in parallel . And in video u said the 2nd job will execute after the completion of first job . Can you please help me in understanding my concern.
One thing more if you change the order of job , say if you call launch() before withTimeoutOrNull() , we see parallel execution BUT if we call withTimeoutOrNull() before launch() , we see sequential execution !!
Happy coding.
What a start xD
You are doing great job.. :)
Why println(...) instead of Log.d(...)?
bro is there a way to run a task in Coroutines for 5 sec intervals indefinitely. cancelled only when i call cancel function.
currently im doing this with Handler and its post delayed method with a runnable
Yep that's very simple. There's a repeat{} builder. You can just put a 5 second delay in it
Very helpful.Keep it up.
would it be better to use OKHTTP?
You still need to use okhttp/retrofit/whatever
@@codingwithmitch what i mean is about setting the timeout in OKHTTP instead of setting it in coroutines. which is better? anyways thank you so much to all of your video tutorials. it means a lot for me =)
@@josephtorres7091 I prefer coroutines
good explanation, thanks!
This is nice and beautiful, looking forward to your new course. Quick question: is the new project using Paging lib from jetpack? I'd love to see using that :)
Probably not. I don't like it really. I found it overly complex
I'm confused, why doesn't Coroutine provide an event listener, I've been browsing about it, all of them are custom listeners, any body here has the same problem?
There is a listener. But it's experimental right now: kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/invoke-on-completion.html.
I show you how to use it in my powerful android apps with jetpack architecture course: codingwithmitch.com/courses/powerful-android-apps-with-jetpack-architecture/
you're the best!!!!!!
I am not familiar with Kotlin coroutines as yet, but I suspect that the delay() function only guarantees a minimum delay of that number of milliseconds (the docs say it depends on the dispatcher as to how it is timed). Your first run probably amounted to just over 2100ms because the delays were longer than 1000ms.
hi mitch. when you should start the course build rest api with kotlin.......
Still building the app.
When will Open API Android App lectures be available and how many would be there and approx when will the series end of Open Api?
It'll be a big one. The app is much larger than the other courses I've made.
Its hard to say when I'll begin publishing lectures. I'm still designing the app.
thanks sir
Nice video sir
Hi Mitch, Please create video using coroutines with Rxjava.
You wouldn't use rxjava with coroutines. They solve the same problem. Asychronous work
The thing is that when using Retrofit for example you don't have to implement a withTimeoutOrNull. That's because the timeout is configured in the library. So perhaps the next video should be (just suggesting) on handling errors in Coroutines (which one of them is SOCKETTIMEOUTEXCEPTION)
Retrofit timeout is a pain. It's much easier to handle with Kotlin. You can cancel or timeout at any time and very easy update the UI
@@codingwithmitch Not really if you use an interceptor. Don't know if you are refering to the same case:
.connectTimeout(100, TimeUnit.SECONDS) .readTimeout(100, TimeUnit.SECONDS) which after build() returns the OkHttpClient.
@@coroutinedispatcher yes I know what you're talking about. It's not ideal to use in something like a NetworkBoundResource class as recommended with mvvm architecture in google sample github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/repository/NetworkBoundResource.kt . At least I've tried and it was not easy to handle the logic. If you have an example I'd love to see. Having a coroutine job pattern with a timeout fits in very nicely.
Hi Mitch, Can you make video on "Koin" library usage, it's option for Dagger in Kotlin. It would be great if you do so. Thanks for videos really helpful. Happy coding.
Yeah I will this year sometime
Awesome
Awesome , thanks for this series of tutorial. I have a question. I want to get request to network every 3 seconds and in the some condition stop it. I use coroutines for network request. Except post handler, Is there another way to do this work ?
You could just do a while loop with a 3 second delay inside. Then if some condition cancel the job.
while(conditionIsTrue){
launch{
networkMethod()
delay(3000)
}
}
@@codingwithmitch I try your solution. But The UI have freezed. I create network request in the this repository : class ProcessRepository @Inject constructor(private val apiService: ApiService) {
val _networkState = MutableLiveData()
val _networkState_first = MutableLiveData()
val completableJob = Job()
private val coroutineScope = CoroutineScope(Dispatchers.IO + completableJob)
private val brokerProcessResponse = MutableLiveData()
fun repeatRequest(processId:String):MutableLiveData{
var networkState = NetworkState(Status.LOADING, userMessage)
_networkState.postValue(networkState)
coroutineScope.launch {
val request = apiService.repeatRequest(processId, token)
withContext(Dispatchers.Main) {
try {
val response = request.await()
if (response.isSuccessful) {
brokerProcessResponse.postValue(response.body())
var networkState = NetworkState(Status.SUCCESS, userMessage)
_networkState.postValue(networkState)
} else {
var networkState = NetworkState(Status.ERROR, userMessage)
_networkState.postValue(networkState)
}
} catch (e: IOException) {
var networkState = NetworkState(Status.ERROR, userMessage)
_networkState.postValue(networkState)
} catch (e: Throwable) {
var networkState = NetworkState(Status.ERROR, userMessage)
_networkState.postValue(networkState)
}
}
delay(3000)
}
return brokerProcessResponse
}
And this is code in my fragment:
private fun repeatRequest(){
viewModel.repeatRequest(processId).observe(this, Observer {
if(it!=null){
process=it.process
if(it.process.state== FINDING_BROKER || it.process.state==NONE){
inProgress(true)
}else{
inProgress(false)
}
setState(it!!.process.state!!,it.process)
}
})
}
private fun pullRequest(){
while (isPullRequest){
repeatRequest()
}
}
@@maryamkazemi1307 have you got any solution for it.?
@@atifabbasi7358 yes. You could give me your email and i'll send my code for you
@@maryamkazemi1307 sure text2atif@gmail.com
Thanks a lot.
I'm really wondering what is in the mug!🤔
Water or tea. If it's after 7pm maybe beer.
@@codingwithmitchMitch, are you planning to change to kotlin soon?
@@adams3356 already did
Hi sir,
i like the way you debug your code but why don't you simplify further by using the android debugger by putting breakpoints in your code.
habit I guess
perfect!
In hard times, I enjoy to see the drinking noise from beginning of this video😅😅
make tutorials about animations please
268:0 likes ratio
bro you're killing it
Check out my flutter video
request MultiView Expoxy Library
Хороший)
Tech Lead Intro? LOL
rick and morty