Struggle for life variables. Or how I tried to make life easier for Android developers

There was an idea. Collect a group of important variables in one place so that together they become something more. And when needed, they could be used when the programmer needs values ​​that do not depend on the life cycles and memory release of minimized applications.





Idea

The idea came from a problem. The problem arose out of resentment.





, , , .

, , .

, -, , , . "" . ?

. , , , : , , .



...





? , : bundle ..





? , , ?





, - , -, . , .



SavedStateHandle MVVM. .





()





, , . @Unkillable





:





@Unkillable
data class SampleFragmentState(
    val testValue: Double,
    val testLiveData: MutableLiveData<Double>
) : EmptyState()
      
      



, Parcelize ().





ViewModel. , AndroidViewModel, ViewModel.





class SampleViewModel(
    application: Application,
    savedStateHandle: SavedStateHandle
) : AndroidStateViewModel(application, savedStateHandle) {

    override fun provideState() = createState<UnkillableSampleFragmentState>()
}
      
      



UnkillableSampleFragmentState .





, ViewModel , . , Google SavedStateHandle.





activity?.application?.let { application -> 
    viewModel = ViewModelProvider(this, SavedStateViewModelFactory(application, this))
        .get(SampleViewModel::class.java) 
}
      
      



. ! . , @Parcelize ( ).





.





init {
    // get values example
    Log.d("StateLog", "0 value ${state.testValue}")
    Log.d("StateLog", "1 value ${state.testLiveData?.value}")
}

fun onSetDataClicked() {
    // set values example
    state.testValue = 2.2
    state.updateTestLiveDataValue(3.3) // yourLiveData.value = 3.3
    state.postUpdateTestLiveDataValue(3.3) // yourLiveData.postValue(3.3)
}
      
      



, .





The purpose of this library is to simplify development and offload the developer from writing code, provided that he works with the preservation of the application state. We also managed to clean up the code from all these variables that need to be saved. In addition, now they are logically separated from the general mass and do not clutter the code, which looks pretty nice. However, for now, it only works in MVVM from Google.







UnkillableSavedState GitHub Repository Link








All Articles