LiveData with shared preferences

前端 未结 7 1583
轮回少年
轮回少年 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:04

    Add below dependency in build.gradle(:app)

     implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.6"  // replace with updated version 
     implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.6"// replace with updated version 
    

    Add Below code inyYour preference class/utils

    private var mPrefs: SharedPreferences =
            mContext.getSharedPreferences(AppConstant.PREF_NAME, Context.MODE_PRIVATE)
    
     private val _constSate = MutableStateFlow(mPrefs.getBoolean(IS_NOTIFY,false))
    
    // function for set data to preference and add to Stateflow. 
    
    fun setData(isNotify: Boolean){
           // mPrefs = instance of your preference 
            mPrefs.edit().putBoolean(IS_NOTIFY, isNotify).apply()
            _constSate.value = isNotify
        }
    
    //function for get observer/flow/live boolean value 
    
    fun getNotifyFlow() : StateFlow = _constSate
    

    //get your observer/flow/live value on other class e.g MainActivity.class etc..

     CoroutineScope(Dispatchers.Main).launch{      
         appPreferences.getNotifyFlow().collect{
                       if (it){
                        Log.d("jai","true")
                       }else{
                         Log.d("jai","false")
                       }
                    }
          }
    

提交回复
热议问题