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...
.
.
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_
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.
0 Dislikes...That is just evidence of how amazing this video is!
So far
I'm waiting for your new course, i'm excited to learn MVI architecture
13:18 Yes I absolutely cared about that quick bit of information! It saved me from having to look it up myself!
Thanks for taking an effort to teach us in the easiest way.
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.
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!
Your smooth and clear voice is making the tutorial more enjoyable. You're talented 👏
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
You the real MVP
@@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 :)
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.
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.
Yeah it's tough to keep up
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
yeah I gave the incorrect description. Someone already pointed that out. But thanks
Amazing tutorial, u are my new favorite channel. Have subcribed and liked,
Keep working hard Mr Mitch :D
Great job explaining Singletons!
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.
Very helpful Mitch, as always
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.
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
I needed that One. Thanks Mitch
Very useful Mitch. Thanks a lot.
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.
Thanks Mitch. This video is very helpful for me
34:53 definitely me lol
come back here from MVI course for practice more about kotlin to keep up with the course.
Thanks to the author, great video.
Awesome tutorial mitch
Very good session thanks for c cool video 👌
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.
Great video Mitch. Can you please make a video about MVI architecture. Thanks a lot!
Yep I will
@@codingwithmitch Please we need one more MVI architecture using coroutines + retrofit. Thanks.
@@aks4125 I got a course brother codingwithmitch.com/courses/model-view-intent-mvi-architecture/
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?
Amazing video, learned so much. Can't wait for more videos, thank you for making it!
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?
Hi Mitch great video... Why you did'nt use moshi..? Instead of Gson
Very nice content!!! Lots of thing in single video great!! Thanks #YouRock
Thank you! your video is easy to understand
Why don't you execute "Repository.cancelJobs()" in the MainViewModel.onClear() method?
@codingwithmitch Tq for the tutorial why can't we use .build() inside retrofitBuilder lazy function it give some error of inline functions
Great video 👍 one question is if Retrofit already runs in background thread, why use coroutines?
Looks nicer and more control over what's happening.
to avoid callback hell
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?
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
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?
What if I don't use lazy? If I just initialize the variable, what will be the problem?
You could as well override OnColeared on the ViewModel to call cancel jobs
Mitch you are love.
thanks love you too bro
Thank you so much!, If I could I doin a lot of likes for you.
Thank you for this awesome tutorial!
Awesome tutorial!
Hi, I'm developer from India. I'm wondering that, how do I handle retrofit errors by following this code?
I am also looking for the same...
TL;DR : Put it in a try catch block.
Check kotlin coroutine 101 from Android developers channel to learn more.
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,
Great 36 minutes video. Learn something good.
Hi Mitch,
To handle network related exception do we need to go with Rx or we can handle that through coroutine as well??
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/
@@codingwithmitch
Great
Thanks a lot :)
How do you handle retrofit chain calls with coroutine ?
Great mitch 👍
thanks, here is your comment for the youtube algoritm
Lol thanks
Hi Mitch,
Awesome turorial as always ...
Could ie be possible to make a tutorial about unidirectional data flow as a best practice ?
How to use retrofit service callback class
Really your awesome sir
Can you create a full course on Retrofit with Put, Patch and delete functions?
I have lots codingwithmitch.com/courses/powerful-android-apps-with-jetpack-architecture/
You are amazing man... 🙏🙏🙏
Funny things Id 2 will not work 😁😁
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 ?
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/
great tutorial 👌
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
Great tutorial!!
What is @Expose for?
Is it a good practice to use live data in repository for a very large code base app
I wouldn't use live data in a repository at all. Suspend functions are the way
When are you planning to release your next course on your website?
The MVI course prob in 1-2 weeks then the powerful android apps course
real help man!
This time I noticed Kodein written on the board in the back. Any plans on making videos on that?
Ya eventually. Not sure when tho
Awesome. Thank you.
you know me so well 😙
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
You could use the viewmodelscope. I've been putting the job in the repository.
What if we have an error? For example, no internet connection. This case our app will crash
Thank you🙏 Dhanyawad
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.
Y it's right here man codingwithmitch.com/courses/model-view-intent-mvi-architecture/
The other courses I have are also complete solutions
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
I don't know what usecase pattern is
@@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
How can I show and hide progress dialog on api request and response with this example?
By watching my mvi course my friend codingwithmitch.com/courses/model-view-intent-mvi-architecture/
Awesome thanks
How to use coroutine scope in Android service
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
Can't we cancel job in viewmodelScope like
override fun onCleared() {
//
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.
I want to know how to handle 401,404,500 error using kotlin coroutines
Have you got a tutorial with viewModelScope?
Not on that specifically.
Amazing
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?
What you would actually want to do is have a job object inside the NetworkBoundResource. That way it's unique to the request
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.
I've never seem Room plus Firebase using MVVM structure.
Do you have any slack channel where we can ask questions??
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/
Please make video for kotlin flows
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.
Can you make a complete lecture on Room Persistence Library ?? :(
I have a free course codingwithmitch.com/courses/sqlite-room-persistence-android/
@@codingwithmitch Thank You
Thanks for it
Thank you
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 :)
So the hashcode will only change if the properties of the object change? I always thought (new hashcode) = (new object instance)
@@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.
@@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?
@@codingwithmitch Instead of asking me why don't you check it in the IntelliJ Idea IDE?
@@codingwithmitch Their's hashcodes will be the same.
Should I have separate repositories for each of my view models?
Yes
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(..)
I think you should cancel job in ViewModel when onCleared fun called
Why mvvm is used only in kotlin, is it not possible for java developent??
yes you can use java or kotlin
Is good to change to Kotlin or to maintain in java in android app development.?
@@kumarraja93 I would switch to kotlin
@@codingwithmitch thank you mitch
i don't know why but when i use only IO or Main, it gives an arror. So i have to use Dispatchers.IO
Prob wrong import
great
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?
Probably. I don't usually use it because I usually do asynchronous work in the repository.
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
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