LiveData with shared preferences

前端 未结 7 1565
轮回少年
轮回少年 2020-12-15 05:51

I have a settings screen where I am setting some values. When I set those values it gets saved in shared preferences and these values are needed in my request to the network

7条回答
  •  庸人自扰
    2020-12-15 06:27

    Assuming your network request is already providing you a LiveData class. For example with Retrofit and a CallAdapter like LiveDataCallAdapter.

    Once you have the last observed value by either:

    • Applying a listener for shared preferences OnSharedPreferenceChangeListener, as you already mentioned, to update a MutableLiveData
    • Or using a SharedPreferences LiveData like rharter/SharedPreferenceLiveData.kt

    Then you can apply the previous LiveData to either:

    • A Transformations.switchMap as in UserViewModel.kt (related part quoted below)
    • Or as parameter for MediatorLiveData addSource method.

    This is the related example for the Transformations.switchMap in UserViewModel.kt:

    private val _login = MutableLiveData()
    val login: LiveData
        get() = _login
    val repositories: LiveData>> = Transformations
        .switchMap(_login) { login ->
            if (login == null) {
                AbsentLiveData.create()
            } else {
                repoRepository.loadRepos(login)
            }
        }
    

提交回复
热议问题