Kotlin Singleton Example with MVVM and Coroutines

Поделиться
HTML-код
  • Опубликовано: 20 окт 2024
  • High quality android courses: codingwithmitc...
    In this video I'm going to show you an example of how to use Singleton objects with Kotlin on Android.
    I'll start by talking about:
    Why we use singletons
    When we use singletons
    Then I'll show you two examples:
    *Example1:*
    In the first example I'll build an example single class and print memory address to the log in MainActivity. This is very basic and is meant to introduce you to the concept of a singleton.
    *Example2:*
    The second example will be much more practical. I'm going to use MVVM architecture with a ViewModel, the Repository pattern, Kotlin coroutines and Retrofit.
    I will create a singleton Retrofit Builder and a singleton Repository. I'll explain MVVM architecture and show you the latest and greatest best-practice method to return real data from a server using a GET request with Retrofit.
    Instagram: / codingwithmitch
    Twitter: / mitch_tabian
    Code: github.com/mit...
    .
    .

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

  • @raulkantor
    @raulkantor 4 года назад +12

    you saved my life man! thank you soo much
    this is perfect i understood everything, you're such a great teacher!!!
    i'm gonna be recommending memberships for your website to _EVERYONE_

  • @saadansari1643
    @saadansari1643 3 года назад +1

    Lot of respect for you sir! I want to switch to Kotlin and try to find some good tutorials. I must say no one is better than you in android here on RUclips! Thank you soo much for these videos.

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

    0 Dislikes...That is just evidence of how amazing this video is!

  • @oscarivan7697
    @oscarivan7697 5 лет назад +6

    I'm waiting for your new course, i'm excited to learn MVI architecture

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

    13:18 Yes I absolutely cared about that quick bit of information! It saved me from having to look it up myself!

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

    Thanks for taking an effort to teach us in the easiest way.

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

    Just like your teaching skill a lot, U r a great teacher, the most imp thing in this video is how you build a repository class...Thanks again for the great stuff.

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

    Thank you Mitch!!!
    I love your videos. The subject is very interesting and you speak very clearly with an easy to understand explanation. My English is very basic but I can understand everything that speaks perfectly. Thank you so much!

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

    Your smooth and clear voice is making the tutorial more enjoyable. You're talented 👏

  • @GakisStylianos
    @GakisStylianos 5 лет назад +37

    Timestamps:
    00:00 - Intro
    01:51 - What is a singleton?
    04:26 - Practical example of a simple singleton in code
    06:09 - Actually writing the singleton class
    09:45 - A real, much more practical example
    10:26 - Dependencies required
    11:03 - Start of coding after dependencies are done
    15:20 - Diagram on MVVM (explanation on MVVM and a bit on MVI)
    16:55 - End of explanation on MVVM (and MVI) back to coding
    31:58 - End of coding, wrap up and talk about the upcoming courses

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

      You the real MVP

    • @GakisStylianos
      @GakisStylianos 5 лет назад +11

      @@codingwithmitch No, you are the real MVP for providing us with all this quality free (and quality paid xD) content. I just thought I'd help out some of my fellow learners :)

  • @mikejay8043
    @mikejay8043 4 года назад +3

    Hey, I love your videos! Just for the record , I do care about the little bits of over information you give such as the description of Gson. Every little bit helps paint a picture when I am trying to determine best practices and important libraries. Thanks for the video.

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

    Mitch thats really fascinating. I dont know when I am goanna go with your all courses. Really good stuffs.!!! And its like day by day new libraries and new architecture are showing up. Got so many things to learn man!!! I wish one day i will complete all your courses.

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

    Great video Mitch. One quick note (apologies if people already pointed this out): hashCode is not the object address/reference in memory (unless you didn't override it, in which case, it's default implementation actually is - Kotlin overrides hashCode() for data classes). hashCode() returns hash value of the fields of the instance of the class; in fact, by design, two instances of the same class with the same field values should hash to the same hash code or "equals" wouldn't work.
    What you are looking for is System.identityHashCode(Object) -- docs.oracle.com/javase/6/docs/api/java/lang/System.html#identityHashCode%28java.lang.Object%29

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

      yeah I gave the incorrect description. Someone already pointed that out. But thanks

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

    Amazing tutorial, u are my new favorite channel. Have subcribed and liked,
    Keep working hard Mr Mitch :D

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

    Great job explaining Singletons!

  • @udhdbdjxisskka
    @udhdbdjxisskka 2 года назад +1

    30:32 I think you could've cancel the jobs in the onClear method on viewmodel, that way it would cancel automatically when the activity is destroyed.

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

    Very helpful Mitch, as always

  • @maxmustermann7954
    @maxmustermann7954 4 года назад +2

    As always amazing video and great explanations.
    Quick question: Isnt that way to set LiveData in the Repository a little bit weird? Wouldnt you normally use methods like postValue for that? I've never seen this done like that in Java so I am confused why it is done like this in Kotlin. Thanks in advance.

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

    Your videos would be THE best video if you could teach us to use the design patterns in different scenarios like, login logout session, filling and submitting forms, network check and load content for placeholder, recyclerview with actions, etc

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

    I needed that One. Thanks Mitch

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

    Very useful Mitch. Thanks a lot.

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

    Loving the work you do, thanks. Just a suggestion. You should cancel jobs on the ViewModel onCleared method. It triggers when activity destroyed, basically same thing you do on activity onDestroy method.

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

    Thanks Mitch. This video is very helpful for me

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

    34:53 definitely me lol
    come back here from MVI course for practice more about kotlin to keep up with the course.

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

    Thanks to the author, great video.

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

    Awesome tutorial mitch

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

    Very good session thanks for c cool video 👌

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

    Instead of putting cancelJobs function into onDestroyed wouldn't it be better if we put it into onCleared in viewModel ? Thanks for the great tutorial.

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

    Great video Mitch. Can you please make a video about MVI architecture. Thanks a lot!

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

      Yep I will

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

      @@codingwithmitch Please we need one more MVI architecture using coroutines + retrofit. Thanks.

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

      @@aks4125 I got a course brother codingwithmitch.com/courses/model-view-intent-mvi-architecture/

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

    In the documentation it says that the instance of a Singleton is created the first time you uses it; So, is not created right when you declare it, and this implicitly means that it is lazy initialization. Therefore, isn't redundant to initialize the Singleton by lazy?

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

    Amazing video, learned so much. Can't wait for more videos, thank you for making it!

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

    The viewModelScope is bounded to ViewModel’s lifecycle. It has created to automatically handle cancellation when the ViewModel’s onClear() is called. So if we are going to use that I think we don't need the viewModel.cancelJobs(), Right?

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

    Hi Mitch great video... Why you did'nt use moshi..? Instead of Gson

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

    Very nice content!!! Lots of thing in single video great!! Thanks #YouRock

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

    Thank you! your video is easy to understand

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

    Why don't you execute "Repository.cancelJobs()" in the MainViewModel.onClear() method?

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

    @codingwithmitch Tq for the tutorial why can't we use .build() inside retrofitBuilder lazy function it give some error of inline functions

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

    Great video 👍 one question is if Retrofit already runs in background thread, why use coroutines?

  • @IvanGarcia-sg8hj
    @IvanGarcia-sg8hj 4 года назад

    First of all Thank you for the video! I will become a member as soon as possible.
    I have a question, What if my getUser method needs two parameters? What can I do?

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

    Hey Hi Mitch,
    I really love the way you explain the things...
    So can you please help us on how to handle network errors like 'No Internet', response with error code 404,500 etc in CoroutineScope...
    currently I am getting below error
    FATAL EXCEPTION: DefaultDispatcher-worker-2
    retrofit2.HttpException: HTTP 404 Not Found

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

    HI, for some reason when I initialize job = Job() I get build errors , no matter how many time I try android studio calls it Unresolved , what might be the issue?

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

    What if I don't use lazy? If I just initialize the variable, what will be the problem?

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

    You could as well override OnColeared on the ViewModel to call cancel jobs

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

    Mitch you are love.

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

    Thank you so much!, If I could I doin a lot of likes for you.

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

    Thank you for this awesome tutorial!

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

    Awesome tutorial!

  • @afinasem8471
    @afinasem8471 5 лет назад +5

    Hi, I'm developer from India. I'm wondering that, how do I handle retrofit errors by following this code?

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

      I am also looking for the same...

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

      TL;DR : Put it in a try catch block.
      Check kotlin coroutine 101 from Android developers channel to learn more.

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

      In ApiService, you can change function return type from User to Response and inside Repository set value = user.body, before that you can check if user.isSuccessfull() and also you can wrap the whole thing inside try/catch for exception,

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

    Great 36 minutes video. Learn something good.

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

    Hi Mitch,
    To handle network related exception do we need to go with Rx or we can handle that through coroutine as well??

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

      Yeah you can handle with coroutines. If there's an error just return an error state. ex: github.com/mitchtabian/Open-API-Android-App/blob/master/app/src/main/java/com/codingwithmitch/openapi/ui/DataState.kt.
      If you want to see examples watch this course: codingwithmitch.com/courses/powerful-android-apps-with-jetpack-architecture/

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

      @@codingwithmitch
      Great
      Thanks a lot :)

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

    How do you handle retrofit chain calls with coroutine ?

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

    Great mitch 👍

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

    thanks, here is your comment for the youtube algoritm

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

    Hi Mitch,
    Awesome turorial as always ...
    Could ie be possible to make a tutorial about unidirectional data flow as a best practice ?

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

    How to use retrofit service callback class

  • @kapilmohod1928
    @kapilmohod1928 Год назад

    Really your awesome sir

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

    Can you create a full course on Retrofit with Put, Patch and delete functions?

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

      I have lots codingwithmitch.com/courses/powerful-android-apps-with-jetpack-architecture/

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

    You are amazing man... 🙏🙏🙏
    Funny things Id 2 will not work 😁😁

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

    this is really great thanks. however one thing - how can/do we pass an error message back to the UI using this pattern ? eg. the Retrofit API call fails for whatever reason. can you add this to the example ?

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

      That's what the powerful android apps course is for. Showing you a more detailed use case. There will be an offline cache, error handling, everything you need. codingwithmitch.com/courses/powerful-android-apps-with-jetpack-architecture/

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

    great tutorial 👌

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

    great video but why in Repository.kt you used this method override fun onActive() {} why you not use liveData{} block and emit() function
    and why in viewmodel you not use Repository as DI
    thanx

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

    Great tutorial!!

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

    What is @Expose for?

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

    Is it a good practice to use live data in repository for a very large code base app

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

      I wouldn't use live data in a repository at all. Suspend functions are the way

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

    When are you planning to release your next course on your website?

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

      The MVI course prob in 1-2 weeks then the powerful android apps course

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

    real help man!

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

    This time I noticed Kodein written on the board in the back. Any plans on making videos on that?

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

    Awesome. Thank you.

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

    you know me so well 😙

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

    shouldn't the co routine be written in viewmodel coroutine scope so that when activity or fragment gets destroyed the coroutine gets cancelled automatically but in your case the network repository coroutine is still running or waiting for the data?? may be i am wrong

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

      You could use the viewmodelscope. I've been putting the job in the repository.

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

    What if we have an error? For example, no internet connection. This case our app will crash

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

    Thank you🙏 Dhanyawad

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

    Thank you, it is very helpful. Can you show the error handling with this example like 404 or No Internet connection and Progress loader, so that it will a complete solution? waiting for the tutorial.

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

      Y it's right here man codingwithmitch.com/courses/model-view-intent-mvi-architecture/

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

      The other courses I have are also complete solutions

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

    Hi Mitch
    your tutorial is very awesome i will subscribe in you website asap
    but i need to ask you about if u are using usecase pattern or not and koin for DI and TTD
    Thank you again for awesome explanation

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

      I don't know what usecase pattern is

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

      @@codingwithmitch
      You can see this article and you will understand me
      “Android clean architecture with ViewModel, UseCases and Repositories: Part 1” by Antoni Castejón García proandroiddev.com/android-clean-architecture-with-viewmodel-usecases-and-repositories-part-1-b9e63889a1aa

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

    How can I show and hide progress dialog on api request and response with this example?

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

      By watching my mvi course my friend codingwithmitch.com/courses/model-view-intent-mvi-architecture/

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

    Awesome thanks

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

    How to use coroutine scope in Android service

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

    Hi Mitch:
    i have one question
    in callback what is mean this part
    "Code that heavily uses callbacks can become hard to read and harder to reason about"
    developer.android.com/courses/extras/multithreading#callbacks

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

    Can't we cancel job in viewmodelScope like
    override fun onCleared() {
    //

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

      I prefer to do it in the repository because I like to create a new job for each event. If I canceled the ViewModelScope it would cancel all jobs instead of just the single event.

  • @ajaysharma-ez5ms
    @ajaysharma-ez5ms 5 лет назад

    I want to know how to handle 401,404,500 error using kotlin coroutines

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

    Have you got a tutorial with viewModelScope?

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

    Amazing

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

    What will happen when you call another getUser while previous is not completed? Don't you should call job.cancel() in the beginning of Repository.getUser?

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

      What you would actually want to do is have a job object inside the NetworkBoundResource. That way it's unique to the request

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

      Actually I missunderstood what you were asking. You don't need to because of the switchmap. The unique properties of a switchmap ensure only one observable is emitted at any given time. So if you searched again it would be terminated already through the switchmap.

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

    I've never seem Room plus Firebase using MVVM structure.

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

    Do you have any slack channel where we can ask questions??

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

      Discord channel. But it's for members only. codingwithmitch.com/enroll/
      With a membership you get access to all my courses and offline downloads codingwithmitch.com/courses/

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

    Please make video for kotlin flows

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

    You are giving a bad example of using singletons everywhere. I guess it's just to show that they exist, but you forgot to mention how bad it will be fot testing everything when only singletons are used.
    And in Repository.kt if you call getUser twice, you will be able to cancel only last job since you overwrite your job variable. And simple fix like canceling job before rewriting it won't work either cuz u may use this function all over your app and it's not ok to expect it not to work sometimes. This place need some refactoring. A guess this is, again, for demonstration purposes but the devil is in the details. You had to at least mentioned it.
    Apart from those small but very important details, great vid.

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

    Can you make a complete lecture on Room Persistence Library ?? :(

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

      I have a free course codingwithmitch.com/courses/sqlite-room-persistence-android/

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

      @@codingwithmitch Thank You

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

    Thanks for it

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

    Thank you

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

    CodingWithMitch , please have a look what does "hashCode" really mean, how it is generated and then eventually use it to prove your theories. As in your example the hashcode is the same. before and after the rotation, because of the properties of the singleton object not because of the address of the singleton in the memory. Please edit your video, so the people that are going to watch the video, won't be misguided. Good luck :)

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

      So the hashcode will only change if the properties of the object change? I always thought (new hashcode) = (new object instance)

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

      @@codingwithmitch hashcode is generated based on the values of the object members. For example if you create another singleton object with the same object property values, the hashcode would be the same. The rule is that objects with equal property values have the same hashcode,and that's why if you'd like to have equals working you have to have equal hashcodes for the objects you are comparing.

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

      @@slavromanov1637 Interesting. Thanks for clearing that up. Just to make sure I understand correctly. Consider this example:
      I have a singleton POJO with two string parameters. If I set the two string parameters to some values (call them "val1" and "val2"). Then do a config change or however you want to force the object to be destroyed. If I create another singleton and set the values to the exact same ("val1" and "val2"), it will have the same hashcode?

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

      @@codingwithmitch Instead of asking me why don't you check it in the IntelliJ Idea IDE?

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

      @@codingwithmitch Their's hashcodes will be the same.

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

    Should I have separate repositories for each of my view models?

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

    I like your video's very much, but hashCode is NOT a memory address in any way. For that you will have to do something like sun.misc.Unsafe.getAddress(..)

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

    I think you should cancel job in ViewModel when onCleared fun called

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

    Why mvvm is used only in kotlin, is it not possible for java developent??

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

      yes you can use java or kotlin

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

      Is good to change to Kotlin or to maintain in java in android app development.?

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

      @@kumarraja93 I would switch to kotlin

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

      @@codingwithmitch thank you mitch

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

    i don't know why but when i use only IO or Main, it gives an arror. So i have to use Dispatchers.IO

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

    great

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

    Hello Mitch
    I am new to your videos. Can you possibly sometime do video on viewmodelscope available in androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0?

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

      Probably. I don't usually use it because I usually do asynchronous work in the repository.

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

    hey mitch i realy like to give u money for course but i dont have: ... WISH i could reach to your member required Courses in your site

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

    Thanks, Mitch, Now I am learning THings that I could not learn before. I wrote a complete repo for this lesson. I mean to show the view too: github.com/Sanaebadi97/Simple-MvvM-Sample