想知道我的架构组件是否正确

时间:2019-01-29 13:12:53

标签: android android-architecture-components android-viewmodel

我是android体系结构组件中的新手,这是我的代码,用于使用kotlin处理viewmodel,repository,retrofit 2

我的活动代码:

lateinit var mainViewModel: MainViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    mainViewModel=ViewModelProviders.of(this).get(MainViewModel::class.java)
    mainViewModel.getUsers().observe(this, Observer<MutableList<User>> {
        it?.forEach {
            Log.v("this", "name " + it.name + " " + it.famil)
        }
    })

}

我的视图模型:

class MainViewModel(application: Application) : AndroidViewModel(application) {
private val mainRepository:MainReposioty=MainReposioty()
private lateinit var users: MutableLiveData<MutableList<User>>

fun getUsers(): MutableLiveData<MutableList<User>> {
    if (!::users.isInitialized) {
        users =mainRepository.getUsers()
    }
    return users
}
}

我的资料库:

class MainReposioty {
private lateinit var getUserList: getUsersApi
private lateinit var users: MutableLiveData<MutableList<User>>

fun getUsers():MutableLiveData<MutableList<User>> {
    if(!::users.isInitialized){
        users= MutableLiveData()
    }
    getUserList = ApiConnection.client.create(getUsersApi::class.java)
    getUserList.getUsers()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe({ result ->
            users += result.users

        }, { error ->
            Log.v("this", error.localizedMessage.toString())
        }
        )

    return users;
}

operator fun <T> MutableLiveData<MutableList<T>>.plusAssign(values: List<T>) {
    val value = this.value ?: arrayListOf()
    value.addAll(values)
    this.value = value
}
}

其他代码适合从webservice提取数据。我想知道我的代码是否正确并以正确的方式

0 个答案:

没有答案