(RxJava3) If you're creating an observable to emit...
# compose
d
(RxJava3) If you're creating an observable to emit values and subscribing in your composable with
subscribeAsState()
, is there a way to unsubscribe from that? Code in thread
I know you can create a disposable and get rid of that, but as far as I know you cannot use the
subscribeAsState()
function with a disposable. I'm creating my observable with
Copy code
private var obsVal =
    Observable.interval(20, TimeUnit.MILLISECONDS).subscribeOn(<http://Schedulers.io|Schedulers.io>()).share()
and would like to be able to reset it, but I'm unsure how to unsub with compose's function
l
it will get unsubscribed with the
subscribeAsState()
call is no longer in the composition. For instance, in the code:
Copy code
if (condition) { val x = y.subscribeAsState() }
The subscription would be removed when condition turned
false
it’s hard to tell without seeing more of your code, but you might find
key
useful here
Copy code
val value by key(index) { getSOmeObservable(index).subscribaAsState() }
in this case, whenever
index
changes, the code inside of it will be a “new” part of the composition, and the previous one will get removed, and thus, unsubscribed
not sure if that makes sense. if not, shoot over some more of the code you’re wanting to write and i might be able to be more helpful
d
Is there any documentation for
key
? I can send over some code too
Copy code
@Composable
fun renderGraph(plotType: PlotType) {
    // state
    val state = obsVal.subscribeAsState(initial = 0).value
    var plotState: PlotType by remember(calculation = { mutableStateOf(PlotType.PLOT0) })
    AndroidView(
        factory = {
            // create the chart
            // set the correct chart type when first building
            plotState = plotType
        },
        modifier = Modifier.fillMaxSize(),
        update = {
            // how the view knows to reset the graph
            if (plotType != plotState) {
                // update the chart data from $state
                // update the flag    
                plotState = plotType
                //TODO: reset the observable to emit values from 0 again
            }
        }
}
I'm calling this in a main view using the following
Copy code
@Composable
fun MainView() {
    // state
    var tabPosition by remember(calculation = { mutableStateOf(0) })
    Column {
        TabRow(selectedTabIndex = tabPosition, tabs = {
            tabs.forEach { plotType ->
                Tab(selected = plotType.value == tabPosition, onClick = {
                    tabPosition = plotType.value
                },
                    text = { Text("Graph: ${plotType.value}") })
            }
        })
        renderGraph(PlotType.fromInt(tabPosition)!!)
    }
}