Network Timeouts with Kotlin Coroutines

Поделиться
HTML-код
  • Опубликовано: 23 янв 2025

Комментарии • 97

  • @dhruvtatran5744
    @dhruvtatran5744 5 лет назад +30

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

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

  • @gabormiklay9209
    @gabormiklay9209 5 лет назад +9

    coroutines is just perfect. it will replace a lot of inconvenient stuff.
    thx for the 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.

  • @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 🤢

  • @ChandanYadav-uj1mv
    @ChandanYadav-uj1mv 5 лет назад +4

    Thanks man for making these series 👍

  • @Since1059
    @Since1059 4 года назад +1

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

  • @AntonioGonzalezsanchez
    @AntonioGonzalezsanchez 5 лет назад +1

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

  • @samha1513
    @samha1513 5 лет назад +8

    Awesome and thanks for the great content .

  • @VenewebTV
    @VenewebTV 3 года назад

    Very usefull, excellent video regards from Caracas, Venezuela

  • @sudhir1274
    @sudhir1274 4 года назад

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

  • @radumarinescu355
    @radumarinescu355 5 лет назад

    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  5 лет назад +2

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

  • @bjugdbjk
    @bjugdbjk 4 года назад

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

  • @kurok1132
    @kurok1132 4 года назад

    Your tutorial videos are sooooooo useful. Thanks man!

  • @harveytai3181
    @harveytai3181 5 лет назад +2

    Awesome, I hope I can get more videos about coroutine

  • @abhishektripathi6957
    @abhishektripathi6957 3 года назад

    Love your content and the way you explain.

  • @blueheartorangeheart3768
    @blueheartorangeheart3768 4 года назад +1

    Are coroutines analogous to contextualized JavaScript Promises?

  • @atifabbasi7358
    @atifabbasi7358 4 года назад

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

  • @erluxman
    @erluxman 5 лет назад +3

    likes it, loves it. wants more.

  • @androidpc9656
    @androidpc9656 2 года назад

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

  • @bro_chenzox
    @bro_chenzox 4 года назад

    Calm and essential. Super!

  • @technics6215
    @technics6215 2 года назад

    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?

  • @shailendraharinkhede9728
    @shailendraharinkhede9728 5 лет назад +3

    Cool.. 👍
    Make more videos on Coroutines.

  • @oscarperry641
    @oscarperry641 4 года назад

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

  • @prasadwalvekar
    @prasadwalvekar 5 лет назад

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

  • @hellosagar
    @hellosagar 5 лет назад

    Can understand withTimeout Vs withTimeoutOrNull
    And Love You Sir

  • @mohdaquib1638
    @mohdaquib1638 4 года назад

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

  • @sogodeveloper7015
    @sogodeveloper7015 5 лет назад

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

  • @muazzamabbas7656
    @muazzamabbas7656 5 лет назад +2

    @CodingWithMitch Please make more videos.

  • @slkslkful
    @slkslkful 5 лет назад +2

    Very good video

  • @Sreekantbehera07
    @Sreekantbehera07 5 лет назад +1

    I really like the way u explain..

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

  • @raulastete3035
    @raulastete3035 5 лет назад +1

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

  • @codingwithphantom3607
    @codingwithphantom3607 4 года назад

    Love your videos bro

  • @samo92mx
    @samo92mx 5 лет назад

    Hi, why you dont use ".await"?

  • @manishsahu4053
    @manishsahu4053 5 лет назад

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

  • @nasiralityagi
    @nasiralityagi 5 лет назад +1

    Happy coding.

  • @savin1999
    @savin1999 5 лет назад +3

    What a start xD

  • @ajaykumarvishwakarma4720
    @ajaykumarvishwakarma4720 3 года назад

    You are doing great job.. :)

  • @technics6215
    @technics6215 2 года назад

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

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

  • @RichaHope
    @RichaHope 5 лет назад

    Very helpful.Keep it up.

  • @josephtorres7091
    @josephtorres7091 4 года назад

    would it be better to use OKHTTP?

    • @codingwithmitch
      @codingwithmitch  4 года назад

      You still need to use okhttp/retrofit/whatever

    • @josephtorres7091
      @josephtorres7091 4 года назад

      @@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  4 года назад +1

      @@josephtorres7091 I prefer coroutines

  • @fahrican9708
    @fahrican9708 4 года назад

    good explanation, thanks!

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

  • @RamanaPtr
    @RamanaPtr 5 лет назад

    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  5 лет назад

      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/

  • @KIRILLINGUSS21
    @KIRILLINGUSS21 5 лет назад +2

    you're the best!!!!!!

  • @cbnewham_ai
    @cbnewham_ai 3 года назад

    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.

  • @sayidaliahmedelmi7988
    @sayidaliahmedelmi7988 5 лет назад

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

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

  • @harloom9603
    @harloom9603 5 лет назад +2

    thanks sir

  • @rahhi9792
    @rahhi9792 5 лет назад +1

    Nice video sir

  • @mnouman6736
    @mnouman6736 5 лет назад

    Hi Mitch, Please create video using coroutines with Rxjava.

    • @codingwithmitch
      @codingwithmitch  5 лет назад

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

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

  • @ajitdalvi8969
    @ajitdalvi8969 5 лет назад

    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.

  • @jitendrakumar3385
    @jitendrakumar3385 5 лет назад +1

    Awesome

  • @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 5 лет назад

      ​@@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 4 года назад

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

    • @maryamkazemi1307
      @maryamkazemi1307 4 года назад +1

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

    • @atifabbasi7358
      @atifabbasi7358 4 года назад

      @@maryamkazemi1307 sure text2atif@gmail.com

  • @tanvibenmandanaka2694
    @tanvibenmandanaka2694 3 года назад

    Thanks a lot.

  • @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 5 лет назад

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

    • @codingwithmitch
      @codingwithmitch  5 лет назад +1

      @@adams3356 already did

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

  • @serggio88888
    @serggio88888 4 года назад

    perfect!

  • @shil331
    @shil331 3 года назад

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

  • @AhmedAli-jx9ie
    @AhmedAli-jx9ie 5 лет назад

    make tutorials about animations please

  • @abhiraj.sharma
    @abhiraj.sharma 5 лет назад

    268:0 likes ratio
    bro you're killing it

  • @jarimanis6908
    @jarimanis6908 5 лет назад

    request MultiView Expoxy Library

  • @jonykestwil4611
    @jonykestwil4611 4 года назад

    Хороший)

  • @dhananjaywithme
    @dhananjaywithme 3 года назад

    Tech Lead Intro? LOL

  • @theonlyarjun
    @theonlyarjun 4 года назад

    rick and morty