Android / Kotlin / Programming

Avoid referencing resources in ViewModel Android

TL;DR

Referencing Resources like stringResource(R.string.text_id) in ViewModel is anti-pattern. The recommended practice is to expose the id of the resource.

Detail

The post by Android Developers says that the recommended practice is to avoid dealing with objects that have a lifecycle in ViewModels.

For example, if a user change his location like from Japan to China, ViewModel is not recreated. This causes that some part of the app UI is Japanese and others are Chinese. In order to avoid this, ViewModel should not deal with objects have a lifecycle.

Code Example

class TestViewModel : ViewModel() {
  val testVariable = ObservableInt()
  
  fun testFunction() {
    testVariable.set(R.string.text_id)
  }
}

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です