ViewModel - Ki-Kobayashi/Android-Wiki GitHub Wiki

🟩 ViewModel で Context を使う

ViewModel で Context を使う場合、以下のように ViewModel ではなくて AndroidViewModel を継承することで Context を使えるようになる

getApplication()

🟡 Hilt使用なら、以下も

@HiltViewModel
class NewsViewModel @Inject constructor(
    @ApplicationContext val appContext: Context, 👈追加
    private val newsRepository: NewsRepository,
): ViewModel() {
    // 【LiveData使用の場合】監視したい値の定義(変更はこのクラスでのみ行うようにする)
    private val _newsHeadLines = MutableLiveData<ApiResource<NewsResponse>>()
    val newsHeadLines: LiveData<ApiResource<NewsResponse>> get() = _newsHeadLines
    
    fun fetchNewsHeadLines(country: String, page:Int) {
        appContext.getString(R.string.app_name) 👈追加

🟡

.

🟩

🟡

.

🟩

🟡

.

🟩

🟡

.

🟩

🟡

.

🟩

🟡

.

🟩

🟡

.

🟩

🟡

.

🟩

🟡

.