How It's Made
Using RxJava autoConnect() and Relay to host a stream in a ViewModel
TL;DR
To preserve and share the state of a stream (e.g. for rotations, dialogs), we can host the stream in Android’s ViewModel by using .replay(1).autoConnect() to share the stream’s state and a Relay to share the input.
For example:
class MyViewModel : ViewModel() {val inputStream = PublishRelay.create<Input>()val viewsState: Observable<ViewState> = inputStream // Transformed to a stream of view states .toViewState() // Shared between subscribers .replay(1).autoConnect(1) { disposables.add(it) } }
Full example here.
Sharing the state
When disposing a connection to an Observable that is a not a ConnectableObservable, the entire stream is disposed.
For example, when subscribing to a network request in an Activity, we lose the state on rotation (or any other configuration change):
endpoint
.getData()
.subscribe { // Create a connection
titleView.text = ... // Present the data
}
.let { disposables.add(it) } // To be disposed in onDestroy()
Most Recent in How It's Made
How It's Made
One Model to Serve Them All: How Instacart deployed a single Deep Learning pCTR model for multiple surfaces with improved operations and performance along the way
Authors: Cheng Jia, Peng Qi, Joseph Haraldson, Adway Dhillon, Qiao Jiang, Sharath Rao Introduction Instacart Ads and Ranking Models At Instacart Ads, our focus lies in delivering the utmost relevance in advertisements to our customers, facilitating novel product discovery and enhancing…...
Dec 19, 2023How It's Made
Monte Carlo, Puppetry and Laughter: The Unexpected Joys of Prompt Engineering
Author: Ben Bader The universe of the current Large Language Models (LLMs) engineering is electrifying, to say the least. The industry has been on fire with change since the launch of ChatGPT in November of…...
Dec 19, 2023How It's Made
Unveiling the Core of Instacart’s Griffin 2.0: A Deep Dive into the Machine Learning Training Platform
Authors: Han Li, Sahil Khanna, Jocelyn De La Rosa, Moping Dou, Sharad Gupta, Chenyang Yu and Rajpal Paryani Background About a year ago, we introduced the first version of Griffin, Instacart’s first ML Platform, detailing its development and support for end-to-end ML in…...
Nov 22, 2023