Yoav Gross
10/02/2019, 2:10 PMrxjava
events and consume them as flow
, it seems i’m not subscribing correctly with flow or missing to correlating action to rx subscribe
This is the flow
usage, i’m expecting to collect each change to the data from the flowable
i’m listening to:
runBlocking {
getSubtitleFromProjectDataManager()
}
private suspend fun getSubtitleFromProjectDataManager() {
scope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
val flow = projectDataManager.getProjectNameFlowable().asFlow()
flow.collect {
subtitle = it
}
launch(Dispatchers.Main) {
view?.rebindToolbar()
}
}
}
This is the rxjava code I’m trying to listen to. Indeed the event isn’t firing again when the data is changed, so I suspect as said before there is a subscription issue:
public Flowable<String> getProjectNameFlowable() {
return RxJavaInterop.toV2Flowable(
getSelectedProject()
.switchMap(projectEntity -> {
Timber.e("fire projectEntity " + projectEntity.title());
return Observable.just(projectEntity.title());
}
));
}
louiscad
10/02/2019, 2:13 PMYoav Gross
10/02/2019, 2:15 PMlouiscad
10/02/2019, 2:18 PMreline
10/02/2019, 3:17 PMflow.collect { ... }
is blocking.
launch(Dispatchers.Main) {
view?.rebindToolbar()
}
I would also suggest that you wrap your suspend function body in coroutineScope { ... }
to prevent leaks Yoav Gross
10/02/2019, 6:33 PMreline
10/02/2019, 6:42 PMflow.collect {
withContext(Dispatchers.Main) {
subtitle = it
view?.rebindToolbar()
}
}
also take a look here if you can use experimental APIs https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flow-on.htmlYoav Gross
10/02/2019, 6:50 PMlouiscad
10/02/2019, 8:44 PMflow.collect {
withContext(Dispatchers.Main) {
subtitle = it
view?.rebindToolbar()
}
}
switches dispatcher on each new value, which is inefficient. Switch dispatcher once for all at collect site (wrapping the whole collect
call) if you want to do that. For flow source/emitter, there's the flowOn
operator as said earlier.reline
10/02/2019, 8:51 PMcollect
call inside withContext(Main)
cause it to observe on the main thread as well? how would you go about observing on IO and then consuming events on Main (without using flowOn
)?louiscad
10/02/2019, 9:13 PMflowOn
) is an implementation detail. The Flow should be safe to collect on the main thread.