Android¶
ReactiveUI.AndroidX connects ReactiveUI to Android through the AndroidX support libraries. Add it by following
Installation. ReactiveUI.AndroidX also ships as
ReactiveUI.AndroidX.Reactive, built from the same source, for an app that uses System.Reactive.
Android walks through every pattern below with a school timetable app. For
an app that does not use AndroidX, the core ReactiveUI package's Android build adds ReactiveActivity,
SharedPreferencesExtensions and UsbManagerExtensions.
Guidelines¶
- View models inherit from
ReactiveObject. They stay free of any Android type. So you can unit test them without a device or an emulator. - Activities, fragments and dialogs inherit from the reactive base classes.
ReactiveAppCompatActivity<TViewModel>,ReactiveFragmentActivity<TViewModel>,ReactiveFragment<TViewModel>,ReactiveDialogFragment<TViewModel>andReactivePreferenceFragment<TViewModel>each implementIViewFor<TViewModel>. Each one exposes aViewModelproperty. You never wire one up by hand. - Wire up controls with
WireUpControls(), notFindViewById.ControlFetcherMixins.WireUpControlsreads a view's properties by reflection. It finds each one's matching resource by name, once, instead of aFindViewByIdcall per control. ItsResolveStrategydecides which properties it wires.Implicitwires every writableView-typed property.ExplicitOptInwires only properties marked to opt in.ExplicitOptOutwires every property except those marked to opt out. - Use
IActivatableViewModelandWhenActivatedfor lifecycle. See When Activated for how a subscription's lifetime follows the view's. - Keep every subscription disposed. See Cleaning up subscriptions and Disposables.
- Convert Android events to streams instead of attaching event handlers. The extension methods in
ReactiveUI.Primitives.ObservableEventsturn an event into anIObservable<T>. Compose it with the rest of a view model's streams. See Events and ObservableEvents. - Bind a list without a hand-written adapter.
ReactiveRecyclerViewAdapter<TViewModel, TCollection>andReactiveRecyclerViewViewHolderbind aRecyclerViewto a collection of view models.ReactivePagerAdapter<TViewModel, TCollection>does the same for aViewPager. - Await an activity result instead of overriding
OnActivityResult.StartActivityForResultAsyncon the reactive activity base classes turns a launched activity's result into aTask. The calling code then reads like ordinary asynchronous code.