difference AndroidViewModel with ViewModel

پرسیده شده
فعالیت 1352 روز پیش
دیده شده 688 بار
0

سلام و احترام خدمت استاد عزیزو دوستان 

سوالی که دارم این هست فرق کلاس ViewModel و AndroidViewModel که هر دو از androidx.lifecycle نشات میگیرند

و باید هنگام ارث بری از AndroidViewModel کانستراکتورش رو implemtnt کنیم و به ما یک instance از کلاس Application میدهد(بر خلاف ViewModel)  

میخواستم بدون چه جاهایی باید از AndroidViewModel ارث بری کنیم 

اگر جواب این هست که جایی که به application نیاز داریم خب این سوال به وجود میاد وقتی خودمون میتونیم به عنوان پارامتر متد کانستراکتور  Application app بدهیم خب چه کاری هستش از AndroidViewModel ارث بری کنیم

تشکر

فایل پیوست

پوریا شفیعی
پوریا شفیعی

29 مرداد 99

2
حذف شده

 

**تاپیک بسته**

 

جواب عالی برای دوستانی که شاید به این سوال برخورد کردند در استک آور فلو:

If you need to use context inside your Viewmodel you should use AndroidViewModel (AVM), because it contains the application context. To retrieve the context call getApplication(), otherwise use the regular ViewModel (VM).

AndroidViewModel has application context. We all know having static context instance is evil as it can cause memory leaks!! However, having static Application instance is not as bad as you might think because there is only one Application instance in the running application.

Therefore, using and having Application instance in a specific class is not a problem in general. But, if an Application instance references them, it is a problem because of the reference cycle problem.

See Also about Application Instance

AndroidViewModel Problematic for unit tests

AVM provides application context which is problematic for unit testing. Unit tests should not deal with any of the Android lifecycle, such as context.

 

فایل پیوست

پوریا شفیعی

توسط

پوریا شفیعی

30 مرداد 99

حذف شده
پوریا جان سلام ممنون از پیگیری و کمک خوبت
Hamidreza Karimi

5 شهریور 99

حذف شده
سالم باشی حمید رضای عزیز
پوریا شفیعی

5 شهریور 99