Android Dev/Compose / / 2022. 4. 28. 01:02

Compose Preview - viewmodel 연결

Viewmodel에 대한 preview를 compose는 제공하지 않는다.

 

따라서 interface나 abstract class를 사용하여 fake Viewmodel을 구성해주어야한다.

 

사용예제는 아래와 같다

 

1. Viewmodel 구성

interface UserViewModelInterface {
    var userFid : String
    var userBasicData : MutableLiveData<UserPublic>
}

object FakeUserViewModel : UserViewModelInterface {
    override var userFid: String = "fakeFid"
    override var userBasicData: MutableLiveData<UserPublic> = MutableLiveData<UserPublic>()
}

@HiltViewModel
class UserViewModel @Inject constructor() : ViewModel(), UserViewModelInterface {

    override var userFid = ""
    override var userBasicData =  MutableLiveData<UserPublic>()

 

2. Compose 구현 예

@OptIn(ExperimentalCoroutinesApi::class)
@Preview(showBackground = true)
@Composable
fun WritingSketchPreview(modifier: Modifier = Modifier) {
    Writing(userViewModel = FakeUserViewModel)

}

@OptIn(ExperimentalCoroutinesApi::class)
@Composable
fun Writing(modifier: Modifier = Modifier, userViewModel : UserViewModelInterface) {
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유