Viewmodel / manage string res

2023. 10. 23. 13:21개발/Kotlin

Solution!

stringres를 사용하는 방법

sealed class AppString{
    data class Res(@StringRes val resId: Int, vararg val arguments: Any): AppString()
    data class Quantity(@StringRes val quantityResId: Int, quantity): AppString
    data class Text(val value: String): AppString()
}

이제 새 AppString클래스는 단일 인터페이스를 제공하여 ViewModel에서 View까지 다양한 유형의 문자열을 정의하는 데 도움이 되며, AppString클래스와 해당 내용이 POJO(또는 POKO)이므로 리소스를 포함할 필요 없이 단위 테스트에서 이를 쉽게 사용할 수 있습니다.

viewstate에서 사용하기

data class ViewState(
  val title: AppString, 
  val message: AppString, 
  val description: AppString
)


fun getViewState() =
    ViewState(
        title = AppString.Resources(R.string.my_title), 
        message = AppString.Resources(R.string.my_formatted_message, arg1), 
        description = AppString.Text("Some static text from api")
    )

viewstate를 사용하지 않는 system에서 전환하기

fun Context.getString(appString: AppString): CharSequence{
  return when(appString){
    is AppString.Res -> {
        if(appString.arguments.isEmpty()){
            getString(appString.resId)
        }else{
            getString(appString.resId, *appString.arguments)
        }
     }

     is AppString.Quantity -> {
        resources.getQuantityText(appString.quantityResId, quantity)
     }

    is AppString.Text -> appString.value
  }
}

jetpack compose의 사용

@Composable 
fun  getString (appString: AppString ) : String { 
  val context = LocalContext.current 
  return  when (appString){ 
    is AppString.Res -> { 
        if (appString.arguments.isEmpty()){ 
            context.getString(appString.resId) 
        } else { 
            context.getString(appString.resId, *appString.arguments) 
        } 
     } 

    는 AppString.Quantity -> { 
        context.resources.getQuantityText(appString.quantityResId, amount) 
     } 

    는 AppString.Text -> appString.value 
  } 
}

Text(text = getString(appString))


Uploaded by N2T

'개발 > Kotlin' 카테고리의 다른 글

Kotlin flow 병렬로 장기 작업 실행  (0) 2023.11.01
to clean code (in Kotlin)  (0) 2023.10.23
__**Using String Resources in a ViewModel**__  (0) 2023.08.08
Retrofit to Ktor  (0) 2023.07.26
Kotlin Unpacking params  (0) 2023.07.26