[go: up one dir, main page]

Skip to content

8. Process Death

James Shvarts edited this page Dec 11, 2018 · 1 revision

Handling Process Death on Android is important. When the app is in the background, it can be killed by the OS at any time to reclaim memory. Roxie is designed to support it by accepting an optional initialState when constructing your ViewModels.

class NoteListViewModel(
    initialState: State?,
    private val loadNoteListUseCase: GetNoteListUseCase
) : BaseViewModel<Action, State>() { ... }

You can save the current State in the Bundle:

    override fun onSaveInstanceState(outState: Bundle?) {
        super.onSaveInstanceState(outState)
        outState?.putParcelable(BUNDLE_KEY_STATE, viewModel.observableState.value)
    }

And then use it when creating your ViewModel:

val initialState: State? = savedInstanceState?.getParcelable(BUNDLE_KEY_STATE)
viewModel = ViewModelProviders.of(this, myViewModelFactory(initialState)).get(MyViewModel::class.java)

Do not save large (> 1MB) objects or lists of data in the Bundle.

To save State in the Bundle, it needs to implement Parcelable. Kotlin's @Parcelize annotation greatly helps reduce the boilerplate:

@Parcelize
data class State(val note: Note? = null,
                 @Transient val isIdle: Boolean = false,
                 @Transient val isLoading: Boolean = false,
                 @Transient val isLoadError: Boolean = false,
                 @Transient val isDeleteError: Boolean = false,
                 @Transient val isDeleted: Boolean = false) : BaseState, Parcelable

Note that we use @Transient annotation for those properties that we don't want to save and later restore. For instance, we don't want to recover from the Process Death scenario only to display the loading indicator to the user.

Clone this wiki locally