Network Timeouts with Kotlin Coroutines

Поділитися
Вставка
  • Опубліковано 1 сер 2019
  • High quality programming courses: codingwithmitch.com/courses
    In this video I show you how to handle network timeouts using Kotlin coroutines.
    In the past, network timeouts have been notoriously difficult to handle on android. AsyncTask, Executors, Threads, all these components made it very difficult to handle errors when making network requests.
    RxJava and LiveData made is slightly simpler, and Kotlin coroutines takes it a step further. With Kotlin coroutines there's many different ways to handle timeouts and cancellations. This is a simple example showing you one of those ways using the "withTimeoutOrNull" coroutine launcher method.
    Instagram: / codingwithmitch
    code: github.com/mitchtabian/Kotlin...
  • Наука та технологія

КОМЕНТАРІ • 97

  • @dhruvtatran5744
    @dhruvtatran5744 5 років тому +30

    "if this is helpful", seriously?
    This is surely very helpful. Thanks for the video.

  • @gabormiklay9209
    @gabormiklay9209 5 років тому +9

    coroutines is just perfect. it will replace a lot of inconvenient stuff.
    thx for the series.

  • @LuisAguilar-hp3lq
    @LuisAguilar-hp3lq 3 роки тому +1

    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

  • @ChandanYadav-uj1mv
    @ChandanYadav-uj1mv 5 років тому +4

    Thanks man for making these series 👍

  • @OggerFN
    @OggerFN 3 роки тому +8

    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.

  • @AntonioGonzalezsanchez
    @AntonioGonzalezsanchez 4 роки тому +1

    These videos are remarkably good. You're really good.

  • @darrenfinch1935
    @darrenfinch1935 4 роки тому +4

    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 🤢

  • @samha1513
    @samha1513 5 років тому +8

    Awesome and thanks for the great content .

  • @Since1059
    @Since1059 4 роки тому +1

    Best video by you for all the new stuff in Android
    Keep Going Good bro, thanks

  • @sudhir1274
    @sudhir1274 4 роки тому

    Another very useful tutorial. Very well put together and explained. Keep up the good work.

  • @kurok1132
    @kurok1132 4 роки тому

    Your tutorial videos are sooooooo useful. Thanks man!

  • @bro_chenzox
    @bro_chenzox 3 роки тому

    Calm and essential. Super!

  • @sogodeveloper7015
    @sogodeveloper7015 4 роки тому

    Great stuff thanks. Look forward to async/await and more on coroutines 👍

  • @abhishektripathi6957
    @abhishektripathi6957 3 роки тому

    Love your content and the way you explain.

  • @oscarperry641
    @oscarperry641 4 роки тому

    Very helpful!! Thank you very Mitch.
    You saved my life!!!!

  • @bjugdbjk
    @bjugdbjk 3 роки тому

    Wow..Kotlin owes u buddy...thanks a lot fr this series...

  • @harveytai3181
    @harveytai3181 5 років тому +2

    Awesome, I hope I can get more videos about coroutine

  • @VenewebTV
    @VenewebTV 2 роки тому

    Very usefull, excellent video regards from Caracas, Venezuela

  • @erluxman
    @erluxman 5 років тому +3

    likes it, loves it. wants more.

  • @shailendraharinkhede9728
    @shailendraharinkhede9728 5 років тому +3

    Cool.. 👍
    Make more videos on Coroutines.

  • @prasadwalvekar
    @prasadwalvekar 5 років тому

    Great stuff!!! And also, you look like G-Eazy in the thumbnail of this video

  • @codingwithphantom3607
    @codingwithphantom3607 3 роки тому

    Love your videos bro

  • @ajaykumarvishwakarma4720
    @ajaykumarvishwakarma4720 3 роки тому

    You are doing great job.. :)

  • @Sreekantbehera07
    @Sreekantbehera07 4 роки тому +1

    I really like the way u explain..

  • @fahrican9708
    @fahrican9708 3 роки тому

    good explanation, thanks!

  • @KIRILLINGUSS21
    @KIRILLINGUSS21 5 років тому +2

    you're the best!!!!!!

  • @RichaHope
    @RichaHope 4 роки тому

    Very helpful.Keep it up.

  • @raulastete3035
    @raulastete3035 4 роки тому +1

    excellent videos ! Thanks! :D I will pay for your courses

  • @mohdaquib1638
    @mohdaquib1638 4 роки тому

    Very helpful Sir. Please also add a full fledged course based on MVVM, Coroutines, Dagger and Unit Testing.

  • @slkslkful
    @slkslkful 5 років тому +2

    Very good video

  • @hellosagar
    @hellosagar 4 роки тому

    Can understand withTimeout Vs withTimeoutOrNull
    And Love You Sir

  • @savin1999
    @savin1999 5 років тому +3

    What a start xD

  • @muazzamabbas7656
    @muazzamabbas7656 5 років тому +2

    @CodingWithMitch Please make more videos.

  • @tanvibenmandanaka2694
    @tanvibenmandanaka2694 2 роки тому

    Thanks a lot.

  • @rahhi9792
    @rahhi9792 5 років тому +1

    Nice video sir

  • @nasiralityagi
    @nasiralityagi 5 років тому +1

    Happy coding.

  • @harloom9603
    @harloom9603 5 років тому +2

    thanks sir

  • @jitendrakumar3385
    @jitendrakumar3385 5 років тому +1

    Awesome

  • @radumarinescu355
    @radumarinescu355 4 роки тому

    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!

    • @codingwithmitch
      @codingwithmitch  4 роки тому +2

      Yeah I do something similar but in the repository. I had the same experiences with Retrofit timeouts. They didn't work as expected.

  • @manishsahu4053
    @manishsahu4053 4 роки тому

    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 !!

  • @byran3019
    @byran3019 5 років тому

    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 :)

    • @codingwithmitch
      @codingwithmitch  5 років тому

      Probably not. I don't like it really. I found it overly complex

  • @serggio88888
    @serggio88888 4 роки тому

    perfect!

  • @blueheartorangeheart3768
    @blueheartorangeheart3768 4 роки тому +1

    Are coroutines analogous to contextualized JavaScript Promises?

  • @technics6215
    @technics6215 Рік тому

    Is there a video about retry with Coroutines?

  • @slvinaykumar
    @slvinaykumar 4 роки тому

    If a suspend function suspends and resumes , how does it runs sequentially in the launch coroutine scope?

  • @atifabbasi7358
    @atifabbasi7358 3 роки тому

    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 .?

  • @ajitdalvi8969
    @ajitdalvi8969 4 роки тому

    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.

  • @androidpc9656
    @androidpc9656 Рік тому

    why suspend funs?
    Are they used only to restrict a fun not to be used outside coroutine scope or other suspend functions ?

  • @abhinandvalasseri1294
    @abhinandvalasseri1294 5 років тому

    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
      @codingwithmitch  5 років тому

      Yep that's very simple. There's a repeat{} builder. You can just put a 5 second delay in it

  • @shil331
    @shil331 2 роки тому

    In hard times, I enjoy to see the drinking noise from beginning of this video😅😅

  • @buzzminkyunghoon3856
    @buzzminkyunghoon3856 5 років тому +1

    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?

    • @codingwithmitch
      @codingwithmitch  5 років тому +2

      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.

  • @samo92mx
    @samo92mx 4 роки тому

    Hi, why you dont use ".await"?

  • @sayidaliahmedelmi7988
    @sayidaliahmedelmi7988 5 років тому

    hi mitch. when you should start the course build rest api with kotlin.......

  • @mnouman6736
    @mnouman6736 4 роки тому

    Hi Mitch, Please create video using coroutines with Rxjava.

    • @codingwithmitch
      @codingwithmitch  4 роки тому

      You wouldn't use rxjava with coroutines. They solve the same problem. Asychronous work

  • @yingxinye4152
    @yingxinye4152 4 роки тому

    Why does the job get launched in withContext(IO) scope? Why not use CoroutineScope(IO){...} in line 30?

    • @yingxinye4152
      @yingxinye4152 4 роки тому

      And you used CoroutineScope(IO){...} in fakeApiRequest() in Async+Await video, which is different from these code

  • @jonykestwil4611
    @jonykestwil4611 3 роки тому

    Хороший)

  • @cbnewham5633
    @cbnewham5633 2 роки тому

    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.

  • @coroutinedispatcher
    @coroutinedispatcher 5 років тому +1

    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
      @codingwithmitch  5 років тому +1

      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

    • @coroutinedispatcher
      @coroutinedispatcher 5 років тому

      @@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.

    • @codingwithmitch
      @codingwithmitch  5 років тому +1

      @@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.

  • @maryamkazemi1307
    @maryamkazemi1307 5 років тому

    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 ?

    • @codingwithmitch
      @codingwithmitch  5 років тому

      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)
      }
      }

    • @maryamkazemi1307
      @maryamkazemi1307 4 роки тому

      ​@@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()
      }
      }

    • @atifabbasi7358
      @atifabbasi7358 3 роки тому

      @@maryamkazemi1307 have you got any solution for it.?

    • @maryamkazemi1307
      @maryamkazemi1307 3 роки тому +1

      @@atifabbasi7358 yes. You could give me your email and i'll send my code for you

    • @atifabbasi7358
      @atifabbasi7358 3 роки тому

      @@maryamkazemi1307 sure text2atif@gmail.com

  • @AhmedAli-jx9ie
    @AhmedAli-jx9ie 5 років тому

    make tutorials about animations please

  • @josephtorres7091
    @josephtorres7091 3 роки тому

    would it be better to use OKHTTP?

    • @codingwithmitch
      @codingwithmitch  3 роки тому

      You still need to use okhttp/retrofit/whatever

    • @josephtorres7091
      @josephtorres7091 3 роки тому

      @@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 =)

    • @codingwithmitch
      @codingwithmitch  3 роки тому +1

      @@josephtorres7091 I prefer coroutines

  • @RamanaPtr
    @RamanaPtr 4 роки тому

    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?

    • @codingwithmitch
      @codingwithmitch  4 роки тому

      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/

  • @technics6215
    @technics6215 Рік тому

    Why println(...) instead of Log.d(...)?

  • @savin1999
    @savin1999 5 років тому

    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.

  • @abhiraj.sharma
    @abhiraj.sharma 4 роки тому

    268:0 likes ratio
    bro you're killing it

  • @jarimanis6908
    @jarimanis6908 5 років тому

    request MultiView Expoxy Library

  • @adams3356
    @adams3356 5 років тому +1

    I'm really wondering what is in the mug!🤔

    • @codingwithmitch
      @codingwithmitch  5 років тому +2

      Water or tea. If it's after 7pm maybe beer.

    • @adams3356
      @adams3356 4 роки тому

      @@codingwithmitchMitch, are you planning to change to kotlin soon?

    • @codingwithmitch
      @codingwithmitch  4 роки тому +1

      @@adams3356 already did

  • @dhananjaywithme
    @dhananjaywithme 2 роки тому

    Tech Lead Intro? LOL

  • @theonlyarjun
    @theonlyarjun 4 роки тому

    rick and morty