### Implement DisposableScope in a Presenter Class in Kotlin Source: https://github.com/badoo/reaktive/blob/master/README.md Provides an example of implementing `DisposableScope` within a `MyPresenter` class in Kotlin. This allows the presenter to manage its subscriptions, ensuring they are disposed of when the presenter is no longer needed, for instance, when its associated view is destroyed. ```kotlin class MyPresenter( private val view: MyView, private val longRunningAction: Completable ) : DisposableScope by DisposableScope() { init { doOnDispose { // Will be called when the presenter is disposed } } fun load() { view.showProgressBar() // Subscription will be disposed when the presenter is disposed longRunningAction.subscribeScoped(onComplete = view::hideProgressBar) } } ``` -------------------------------- ### Install Reaktive Dependencies in Kotlin Multiplatform Source: https://context7.com/badoo/reaktive/llms.txt Add Reaktive and its related dependencies to your Kotlin multiplatform project's commonMain and commonTest source sets. This includes the core 'reaktive' library, 'reaktive-annotations', 'coroutines-interop' for coroutine integration, and 'reaktive-testing' for testing purposes. ```kotlin kotlin { sourceSets { commonMain { dependencies { implementation("com.badoo.reaktive:reaktive:2.4.0") implementation("com.badoo.reaktive:reaktive-annotations:2.4.0") implementation("com.badoo.reaktive:coroutines-interop:2.4.0") // For coroutines interop } } commonTest { dependencies { implementation("com.badoo.reaktive:reaktive-testing:2.4.0") } } } } ``` -------------------------------- ### Configure Gradle for Reaktive Export to Swift Source: https://github.com/badoo/reaktive/blob/master/docs/SwiftInterop.md This Gradle configuration snippet shows how to set up your Kotlin project to export Reaktive libraries for use in Swift. It targets iOS platforms and includes the necessary dependency for the reaktive library. ```Kotlin kotlin { targets .filterIsInstance() .filter { it.konanTarget.family == Family.IOS } .forEach { target -> target.binaries { framework { // Some setup code here export("com.badoo.reaktive:reaktive:") } } } sourceSets { named("commonMain") { dependencies { api("com.badoo.reaktive:reaktive:") } } } } ``` -------------------------------- ### Wrap Reaktive Sources for Swift Generics Source: https://github.com/badoo/reaktive/blob/master/docs/SwiftInterop.md Demonstrates how to use Kotlin's `wrap()` extension functions to expose Reaktive sources like Observable, Single, Maybe, and Completable to Swift. This is necessary because Swift does not support generics for interfaces exported from Kotlin. ```Kotlin class SharedDataSource { fun load(): SingleWrapper = singleFromFunction { // A long running operation "A result" } .subscribeOn(ioScheduler) .observeOn(mainScheduler) .wrap() } class SharedViewModel { private val _state = BehaviorSubject(State()) val state: BehaviorObservableWrapper = _state.wrap() } ``` -------------------------------- ### Pair Elements Sequentially with zip - Kotlin Source: https://context7.com/badoo/reaktive/llms.txt Combines elements from multiple Observables by pairing them based on their emission order. The first element from each source is paired, then the second from each, and so on. If one Observable completes before others, no more zipped emissions occur. ```kotlin import com.badoo.reaktive.observable.zip import com.badoo.reaktive.observable.observableOf import com.badoo.reaktive.observable.subscribe val names = observableOf("Alice", "Bob", "Charlie") val scores = observableOf(95, 87, 92) val grades = observableOf("A", "B+", "A-") // Zip two sources zip(names, scores) { name, score -> "$name scored $score" }.subscribe( onNext = { println(it) } ) // Output: Alice scored 95 // Output: Bob scored 87 // Output: Charlie scored 92 // Zip three sources zip(names, scores, grades) { name, score, grade -> "$name: $score ($grade)" }.subscribe( onNext = { println(it) } ) // Output: Alice: 95 (A) // Output: Bob: 87 (B+) // Output: Charlie: 92 (A-) ``` -------------------------------- ### Implement DisposableScope in an Activity in Kotlin Source: https://github.com/badoo/reaktive/blob/master/README.md Demonstrates how to implement `DisposableScope` in an Android `AppCompatActivity` in Kotlin. By delegating to `DisposableScope`, the activity can automatically manage and dispose of its subscriptions when the activity is destroyed, preventing leaks. ```kotlin class MyActivity : AppCompatActivity(), DisposableScope by DisposableScope() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) MyPresenter(...).scope() } override fun onDestroy() { dispose() super.onDestroy() } } ``` -------------------------------- ### Configure Reaktive Dependencies in Gradle Source: https://github.com/badoo/reaktive/blob/master/README.md This snippet shows how to configure dependencies for the Reaktive library and its modules in a commonMain and commonTest source set using Gradle. It includes dependencies for the core library, annotations, coroutines interop, RxJava interop, and testing utilities. ```groovy kotlin { sourceSets { commonMain { dependencies { implementation 'com.badoo.reaktive:reaktive:' implementation 'com.badoo.reaktive:reaktive-annotations:' implementation 'com.badoo.reaktive:coroutines-interop:' implementation 'com.badoo.reaktive:rxjava2-interop:' implementation 'com.badoo.reaktive:rxjava3-interop:' } } commonTest { dependencies { implementation 'com.badoo.reaktive:reaktive-testing:' } } } } ``` -------------------------------- ### Manage Subscriptions with DisposableScope in Kotlin Source: https://github.com/badoo/reaktive/blob/master/README.md Explains how to use `DisposableScope` in Kotlin for easy subscription management. Subscriptions made within the scope are automatically disposed when the scope is disposed, preventing memory leaks. ```kotlin val scope = disposableScope { observable.subscribeScoped(...) // Subscription will be disposed when the scope is disposed doOnDispose { // Will be called when the scope is disposed } someDisposable.scope() // `someDisposable` will be disposed when the scope is disposed } // At some point later scope.dispose() ``` -------------------------------- ### Convert Reaktive Scheduler to Coroutine Dispatcher in Kotlin Source: https://github.com/badoo/reaktive/blob/master/README.md Shows how to convert a Reaktive `Scheduler` to a Kotlin Coroutine `Dispatcher` and vice versa. This enables seamless integration between Reaktive's threading model and Kotlin Coroutines. ```kotlin val defaultScheduler = Dispatchers.Default.asScheduler() val computationDispatcher = computationScheduler.asCoroutineDispatcher() ``` -------------------------------- ### RxSwift Interoperability with Reaktive Wrappers Source: https://github.com/badoo/reaktive/blob/master/docs/SwiftInterop.md Provides Swift extensions to bridge Reaktive's ObservableWrapper, SingleWrapper, MaybeWrapper, and CompletableWrapper with RxSwift's equivalents. This allows seamless integration of Reaktive data streams within an RxSwift-based Swift project. ```Swift import RxSwift import YourKotlinFramework extension RxSwift.Observable where Element : AnyObject { static func from(_ observable: ObservableWrapper) -> RxSwift.Observable { return RxSwift.Observable.create { observer in let disposable = observable.subscribe( onError: { observer.onError(KotlinError($0)) }, onComplete: observer.onCompleted, onNext: observer.onNext ) return Disposables.create(with: disposable.dispose) } } } extension RxSwift.Single where Element : AnyObject { static func from(_ single: SingleWrapper) -> RxSwift.Single { return RxSwift.Single.create { observer in let disposable = single.subscribe( onError: { observer(.failure(KotlinError($0))) }, onSuccess: { observer(.success($0)) } ) return Disposables.create(with: disposable.dispose) } } } extension RxSwift.Maybe where Element : AnyObject { static func from(_ maybe: MaybeWrapper) -> RxSwift.Maybe { return RxSwift.Maybe.create { observer in let disposable = maybe.subscribe( onError: { observer(.error(KotlinError($0))) }, onComplete: { observer(.completed) }, onSuccess: { observer(.success($0)) } ) return Disposables.create(with: disposable.dispose) } } } extension RxSwift.Completable { static func from(_ completable: CompletableWrapper) -> RxSwift.Completable { return RxSwift.Completable.create { observer in let disposable = completable.subscribe( onError: { observer(.error(KotlinError($0))) }, onComplete: { observer(.completed) } ) return Disposables.create(with: disposable.dispose) } } } struct KotlinError : Error { let throwable: KotlinThrowable init (_ throwable: KotlinThrowable) { self.throwable = throwable } } ``` -------------------------------- ### Coroutines Flow to Reaktive Observable Conversion in Kotlin Source: https://github.com/badoo/reaktive/blob/master/README.md Illustrates the interoperability between Kotlin Coroutines `Flow` and Reaktive `Observable`. It shows how to convert a `Flow` to an `Observable` and vice versa using extension functions. ```kotlin val flow: Flow = observableOf(1, 2, 3).asFlow() val observable: Observable = flowOf(1, 2, 3).asObservable() ``` -------------------------------- ### Control Subscription and Observation Threads with subscribeOn/observeOn Source: https://context7.com/badoo/reaktive/llms.txt Manages which thread or scheduler is used for subscription and observation. This is crucial for performing background operations like network calls or heavy computations while ensuring UI updates occur on the main thread. It takes a scheduler as an argument to define the execution context. ```kotlin import com.badoo.reaktive.observable.observable import com.badoo.reaktive.observable.subscribeOn import com.badoo.reaktive.observable.observeOn import com.badoo.reaktive.observable.subscribe import com.badoo.reaktive.observable.map import com.badoo.reaktive.scheduler.ioScheduler import com.badoo.reaktive.scheduler.computationScheduler import com.badoo.reaktive.scheduler.mainScheduler data class Data(val content: String) fun loadFromNetwork(): Data { // Simulate network call Thread.sleep(1000) return Data("Response from server") } fun parseData(data: Data): String { // CPU-intensive parsing return data.content.uppercase() } val networkObservable = observable { emitter -> emitter.onNext(loadFromNetwork()) emitter.onComplete() } networkObservable .subscribeOn(ioScheduler) // Network call on IO thread .map { parseData(it) } .observeOn(computationScheduler) // Parsing on computation thread .map { "Processed: $it" } .observeOn(mainScheduler) // UI update on main thread .subscribe( onNext = { result -> println("Result: $result") // Called on main thread }, onError = { error -> println("Error: ${error.message}") } ) ``` -------------------------------- ### Create Observable with Manual Emitter in Reaktive Source: https://context7.com/badoo/reaktive/llms.txt Create a custom Observable by manually signaling events (onNext, onError, onComplete) using an emitter. This approach is ideal for wrapping asynchronous operations or implementing complex reactive logic where explicit control over the stream's lifecycle is required. ```kotlin import com.badoo.reaktive.observable.observable import com.badoo.reaktive.observable.subscribe val customObservable = observable { emitter -> try { emitter.onNext("First") emitter.onNext("Second") emitter.onNext("Third") emitter.onComplete() } catch (e: Throwable) { emitter.onError(e) } } val disposable = customObservable.subscribe( onNext = { value -> println("Received: $value") }, onError = { error -> println("Error: ${error.message}") }, onComplete = { println("Completed") } ) // Later: clean up disposable.dispose() ``` -------------------------------- ### Swift Interoperability with Wrapper Classes - Kotlin & Swift Source: https://context7.com/badoo/reaktive/llms.txt Enables interoperability between Kotlin and Swift by exporting Reaktive sources using wrapper classes. This preserves generic type information for Swift consumers. It demonstrates exposing Kotlin's `Single` and `BehaviorSubject` to Swift. ```kotlin import com.badoo.reaktive.single.singleFromFunction import com.badoo.reaktive.single.subscribeOn import com.badoo.reaktive.single.observeOn import com.badoo.reaktive.single.SingleWrapper import com.badoo.reaktive.single.wrap import com.badoo.reaktive.observable.BehaviorObservableWrapper import com.badoo.reaktive.observable.wrap import com.badoo.reaktive.subject.behavior.BehaviorSubject import com.badoo.reaktive.scheduler.ioScheduler import com.badoo.reaktive.scheduler.mainScheduler // Expose Single to Swift class SharedDataSource { fun loadData(): SingleWrapper = singleFromFunction { // Long running operation "Fetched data" } .subscribeOn(ioScheduler) .observeOn(mainScheduler) .wrap() // Wrap for Swift compatibility } // Expose BehaviorSubject state to Swift class SharedViewModel { private val _state = BehaviorSubject(ViewState()) val state: BehaviorObservableWrapper = _state.wrap() fun updateState(newValue: String) { _state.onNext(_state.value.copy(data = newValue)) } data class ViewState( val isLoading: Boolean = false, val data: String? = null ) } ``` ```swift // Swift usage import YourKotlinFramework let dataSource = SharedDataSource() let disposable = dataSource.loadData().subscribe( onError: { error in print("Error: \(error)") }, onSuccess: { data in print("Data: \(data)") } ) let viewModel = SharedViewModel() let stateDisposable = viewModel.state.subscribe( onNext: { state in if state.isLoading { showLoading() } else if let data = state.data { showData(data) } } ) ``` -------------------------------- ### Unit Testing Reactive Streams - Kotlin Source: https://context7.com/badoo/reaktive/llms.txt Provides utilities for unit testing reactive streams. The `TestObservable` allows emitting values and asserting the behavior of subscribed operators. It helps in verifying the correctness of reactive data flows without needing a full environment. ```kotlin import com.badoo.reaktive.test.observable.TestObservable import com.badoo.reaktive.test.observable.assertValues import com.badoo.reaktive.test.observable.test import com.badoo.reaktive.observable.map import com.badoo.reaktive.observable.filter // Create test observable val testObservable = TestObservable() // Subscribe with test observer val observer = testObservable .filter { it > 0 } .map { it * 2 } .test() // Emit test values testObservable.onNext(1) testObservable.onNext(-1) // Filtered out testObservable.onNext(2) testObservable.onComplete() // Assert results observer.assertValues(2, 4) // 1*2, 2*2 (negative filtered) observer.assertComplete() observer.assertNoErrors() ``` -------------------------------- ### Create Observable from Values with Reaktive Source: https://context7.com/badoo/reaktive/llms.txt Create an Observable that emits a sequence of predefined values and then completes. This method is suitable for scenarios where you have a known set of data to be processed reactively. It supports emitting single values, multiple values, or values from an Iterable. ```kotlin import com.badoo.reaktive.observable.observableOf import com.badoo.reaktive.observable.subscribe // Single value val single = observableOf(42) single.subscribe( onNext = { println("Value: $it") }, // Output: Value: 42 onComplete = { println("Done") } // Output: Done ) // Multiple values val multiple = observableOf(1, 2, 3, 4, 5) multiple.subscribe( onNext = { println("Item: $it") }, // Output: Item: 1, Item: 2, ... onComplete = { println("Complete") } ) // From Iterable val list = listOf("a", "b", "c").asObservable() list.subscribe( onNext = { println(it) } // Output: a, b, c ) ``` -------------------------------- ### Use PublishSubject for Multicasting Hot Observables Source: https://context7.com/badoo/reaktive/llms.txt A Subject that multicasts elements to all currently subscribed observers. New subscribers will only receive elements emitted after they have subscribed. This is useful when multiple observers need to react to the same stream of events, but only from the point of their subscription onwards. ```kotlin import com.badoo.reaktive.subject.publish.PublishSubject import com.badoo.reaktive.observable.subscribe val subject = PublishSubject() // First subscriber subject.subscribe( onNext = { println("Observer 1: $it") } ) subject.onNext("Hello") // Output: Observer 1: Hello // Second subscriber joins subject.subscribe( onNext = { println("Observer 2: $it") } ) subject.onNext("World") // Output: Observer 1: World // Output: Observer 2: World subject.onComplete() // Complete all observers ``` -------------------------------- ### Utilize BehaviorSubject for Stateful Hot Observables Source: https://context7.com/badoo/reaktive/llms.txt A Subject that emits the most recent element to new subscribers, along with all subsequent elements. This makes it ideal for representing and managing application state, as new components can immediately access the current state upon subscription. It requires an initial value. ```kotlin import com.badoo.reaktive.subject.behavior.BehaviorSubject import com.badoo.reaktive.observable.subscribe data class AppState( val isLoading: Boolean = false, val data: String? = null, val error: String? = null ) val stateSubject = BehaviorSubject(AppState()) // Current value access println("Current: ${stateSubject.value}") // Output: Current: AppState(...) // Subscribe and immediately receive current value stateSubject.subscribe( onNext = { state -> when { state.isLoading -> println("Loading...") state.error != null -> println("Error: ${state.error}") state.data != null -> println("Data: ${state.data}") } } ) // Output: (initial state) // Update state stateSubject.onNext(stateSubject.value.copy(isLoading = true)) // Output: Loading... stateSubject.onNext(AppState(data = "Fetched data")) // Output: Data: Fetched data // New subscriber immediately gets latest state stateSubject.subscribe( onNext = { println("New subscriber: $it") } ) // Output: New subscriber: AppState(data=Fetched data, ...) ``` -------------------------------- ### DisposableScope: Manage Lifecycle-Aware Subscriptions in Kotlin Source: https://context7.com/badoo/reaktive/llms.txt DisposableScope helps manage subscriptions that should be disposed together, typically tied to a component's lifecycle. It can be used via a builder or as a delegate for classes. Subscriptions made within the scope are automatically cleaned up when the scope is disposed. ```kotlin import com.badoo.reaktive.disposable.scope.DisposableScope import com.badoo.reaktive.disposable.scope.disposableScope import com.badoo.reaktive.observable.observableInterval import com.badoo.reaktive.scheduler.mainScheduler import kotlin.time.Duration.Companion.seconds // Using disposableScope builder val scope = disposableScope { // Subscriptions are automatically scoped observableInterval(1.seconds, mainScheduler) .subscribeScoped( onNext = { tick -> println("Tick: $tick") } ) doOnDispose { println("Cleanup performed") } } // Later: dispose all subscriptions scope.dispose() // Output: Cleanup performed // Using DisposableScope as delegate (recommended for classes) class MyPresenter : DisposableScope by DisposableScope() { fun start() { observableInterval(1.seconds, mainScheduler) .subscribeScoped( onNext = { updateUI(it) } ) } private fun updateUI(tick: Long) { println("Update: $tick") } } // Usage val presenter = MyPresenter() presenter.start() // ... later presenter.dispose() // Cleans up all subscriptions ``` -------------------------------- ### Create Observable from Callable Function in Reaktive Source: https://context7.com/badoo/reaktive/llms.txt Generate an Observable that executes a given function, emits its return value, and then completes. This is useful for integrating synchronous operations into a reactive stream, such as fetching data from a database or performing a calculation. ```kotlin import com.badoo.reaktive.observable.observableFromFunction import com.badoo.reaktive.observable.subscribe data class User(val id: Int, val name: String) fun fetchUserFromDatabase(id: Int): User { // Simulate database lookup return User(id, "John Doe") } val userObservable = observableFromFunction { fetchUserFromDatabase(123) } userObservable.subscribe( onNext = { user -> println("User: ${user.name}") }, onError = { e -> println("Failed: ${e.message}") }, onComplete = { println("Done") } ) // Output: User: John Doe // Output: Done ``` -------------------------------- ### Avoid UI Freezing with isThreadLocal Flag in Kotlin Source: https://github.com/badoo/reaktive/blob/master/README.md Shows how to set the `isThreadLocal` flag to `true` in the `subscribe` operator in Kotlin to achieve non-freezing UI updates. This method allows callbacks like `onNext` and `onComplete` to safely interact with mutable state from the main thread. ```kotlin val values = mutableListOf() var isComplete = false observable { emitter -> // Background job } .subscribeOn(ioScheduler) .observeOn(mainScheduler) .subscribe( isThreadLocal = true, onNext = { values += it }, // Callback is not frozen, we can update the mutable list onComplete = { isComplete = true } // Callback is not frozen, we can change the flag ) ``` -------------------------------- ### Transform and Flatten with flatMap - Kotlin Source: https://context7.com/badoo/reaktive/llms.txt Transforms each element emitted by an Observable into a new Observable and then flattens the resulting Observables into a single output Observable. This is crucial for handling asynchronous operations, like making multiple API calls based on initial data. ```kotlin import com.badoo.reaktive.observable.observableOf import com.badoo.reaktive.observable.flatMap import com.badoo.reaktive.observable.subscribe import com.badoo.reaktive.single.Single import com.badoo.reaktive.single.singleOf import com.badoo.reaktive.single.asObservable data class User(val id: Int, val name: String) data class Order(val userId: Int, val product: String) // Simulate API calls fun fetchUser(id: Int): Single = singleOf(User(id, "User $id")) fun fetchOrders(userId: Int): Single> = singleOf( listOf( Order(userId, "Laptop"), Order(userId, "Phone") ) ) val userIds = observableOf(1, 2, 3) userIds .flatMap { id -> fetchUser(id).asObservable() } .flatMap { user -> fetchOrders(user.id).asObservable() } .subscribe( onNext = { orders -> orders.forEach { println("${it.userId}: ${it.product}") } } ) // With concurrency limit val limitedFlatMap = userIds.flatMap(maxConcurrency = 2) { id -> fetchUser(id).asObservable() } ``` -------------------------------- ### Coroutines Interoperability: Convert Kotlin Flow and Reaktive Observable Source: https://context7.com/badoo/reaktive/llms.txt This snippet demonstrates how to convert between Kotlin Flow and Reaktive Observable, enabling seamless interoperability between coroutines and reactive streams. It covers both Observable to Flow and Flow to Observable conversions. ```kotlin import com.badoo.reaktive.coroutinesinterop.asFlow import com.badoo.reaktive.coroutinesinterop.asObservable import com.badoo.reaktive.observable.observableOf import com.badoo.reaktive.observable.subscribe import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.collect import kotlinx.coroutines.runBlocking // Observable to Flow @OptIn(ExperimentalCoroutinesApi::class) fun observableToFlow() = runBlocking { val observable = observableOf(1, 2, 3, 4, 5) val flow = observable.asFlow() flow.collect { value -> println("From Flow: $value") } } // Flow to Observable fun flowToObservable() { val flow = flowOf("A", "B", "C") val observable = flow.asObservable() observable.subscribe( onNext = { println("From Observable: $it") }, onComplete = { println("Done") } ) } ``` -------------------------------- ### Create Single from Value - Kotlin Source: https://context7.com/badoo/reaktive/llms.txt Creates a Single observable that emits exactly one value. Useful for operations expected to yield a single result, such as API calls or database queries. It handles both successful value emission and error scenarios. ```kotlin import com.badoo.reaktive.single.singleOf import com.badoo.reaktive.single.subscribe import com.badoo.reaktive.single.singleFromFunction import com.badoo.reaktive.single.singleOfError // From a value val single = singleOf("Hello, Reaktive!") single.subscribe( onSuccess = { println(it) }, // Output: Hello, Reaktive! onError = { println("Error: $it") } ) // From a function val computedSingle = singleFromFunction { // Perform computation 42 * 2 } computedSingle.subscribe( onSuccess = { println("Result: $it") } // Output: Result: 84 ) // Error case val errorSingle = singleOfError(IllegalStateException("Failed")) errorSingle.subscribe( onSuccess = { println(it) }, onError = { println("Caught: ${it.message}") } // Output: Caught: Failed ) ``` -------------------------------- ### Avoid UI Freezing with threadLocal Operator in Kotlin Source: https://github.com/badoo/reaktive/blob/master/README.md Demonstrates using the `threadLocal` operator in Kotlin to perform background operations and update UI elements without freezing the main thread. This approach ensures that callbacks like `doOnBeforeNext` and `doOnBeforeFinally` can safely modify shared mutable state. ```kotlin val values = mutableListOf() var isFinished = false observable { emitter -> // Background job } .subscribeOn(ioScheduler) .observeOn(mainScheduler) .threadLocal() .doOnBeforeNext { values += it } // Callback is not frozen, we can update the mutable list .doOnBeforeFinally { isFinished = true } // Callback is not frozen, we can change the flag .subscribe() ``` -------------------------------- ### Create Maybe from Optional Value - Kotlin Source: https://context7.com/badoo/reaktive/llms.txt Creates a Maybe observable that can emit zero or one value. Ideal for scenarios where a result might not be present, such as searching within a collection. It supports emitting a value or completing without a value. ```kotlin import com.badoo.reaktive.maybe.maybeOf import com.badoo.reaktive.maybe.maybeOfEmpty import com.badoo.reaktive.maybe.maybeOfNotNull import com.badoo.reaktive.maybe.subscribe // With a value val withValue = maybeOf("Found!") withValue.subscribe( onSuccess = { println("Success: $it") }, // Output: Success: Found! onComplete = { println("Empty") } ) // Empty maybe val empty = maybeOfEmpty() empty.subscribe( onSuccess = { println("Success: $it") }, onComplete = { println("No value") } // Output: No value ) // From nullable value val nullableValue: String? = null val fromNullable = maybeOfNotNull(nullableValue) fromNullable.subscribe( onSuccess = { println(it) }, onComplete = { println("Was null") } // Output: Was null ) ``` -------------------------------- ### Execute Coroutine Suspending Function with Reaktive Single in Kotlin Source: https://github.com/badoo/reaktive/blob/master/README.md Demonstrates how to execute a suspending Kotlin coroutine function using Reaktive's `singleFromCoroutine`. The result of the coroutine is then subscribed to, printing the output. ```kotlin fun doSomething() { singleFromCoroutine { getSomething() } .subscribe { println(it) } } suspend fun getSomething(): String { delay(1.seconds) return "something" } ``` -------------------------------- ### Implement ReaktivePlugin for Observable Decoration (Kotlin) Source: https://github.com/badoo/reaktive/blob/master/README.md This snippet demonstrates how to implement the ReaktivePlugin interface in Kotlin to decorate Observable sources. It intercepts observable assembly to add error tracing functionality. The plugin can be registered using `registerReaktivePlugin` and unregistered using `unregisterReaktivePlugin`. Dependencies include Reaktive's `ReaktivePlugin`, `Observable`, and `ObservableObserver` interfaces. ```kotlin object MyPlugin : ReaktivePlugin { override fun onAssembleObservable(observable: Observable): Observable = object : Observable { private val traceException = TraceException() override fun subscribe(observer: ObservableObserver) { observable.subscribe( object : ObservableObserver by observer { override fun onError(error: Throwable) { observer.onError(error, traceException) } } ) } } override fun onAssembleSingle(single: Single): Single = TODO("Similar to onAssembleSingle") override fun onAssembleMaybe(maybe: Maybe): Maybe = TODO("Similar to onAssembleSingle") override fun onAssembleCompletable(completable: Completable): Completable = TODO("Similar to onAssembleSingle") private fun ErrorCallback.onError(error: Throwable, traceException: TraceException) { if (error.suppressedExceptions.lastOrNull() !is TraceException) { error.addSuppressed(traceException) } onError(error) } private class TraceException : Exception() } ``` -------------------------------- ### Error Handling: onErrorReturn and onErrorResumeNext in Kotlin Source: https://context7.com/badoo/reaktive/llms.txt This snippet demonstrates two methods for handling errors in Reaktive streams: `onErrorReturn` provides a fallback value when an error occurs, and `onErrorResumeNext` allows switching to an alternative observable stream to recover from errors gracefully. ```kotlin import com.badoo.reaktive.observable.observable import com.badoo.reaktive.observable.onErrorReturn import com.badoo.reaktive.observable.onErrorResumeNext import com.badoo.reaktive.observable.observableOf import com.badoo.reaktive.observable.subscribe // Return default value on error val riskyOperation = observable { emitter -> emitter.onNext(1) emitter.onNext(2) emitter.onError(RuntimeException("Network failed")) } riskyOperation .onErrorReturn { error -> println("Recovered from: ${error.message}") -1 // Default value } .subscribe( onNext = { println("Value: $it") }, onComplete = { println("Complete") } ) // Output: Value: 1 // Output: Value: 2 // Output: Recovered from: Network failed // Output: Value: -1 // Output: Complete // Resume with alternative stream riskyOperation .onErrorResumeNext { error -> println("Switching to fallback") observableOf(100, 200, 300) // Fallback stream } .subscribe( onNext = { println("Value: $it") } ) ``` -------------------------------- ### Implement Rate Limiting with debounce Source: https://context7.com/badoo/reaktive/llms.txt Drops elements that are followed by newer elements within a specified timeout period. This operator is ideal for scenarios like search-as-you-type, where you only want to trigger an action after the user has paused typing for a short duration. It requires a timeout duration and a scheduler. ```kotlin import com.badoo.reaktive.observable.debounce import com.badoo.reaktive.observable.subscribe import com.badoo.reaktive.scheduler.mainScheduler import com.badoo.reaktive.subject.publish.PublishSubject import kotlin.time.Duration.Companion.milliseconds val searchInput = PublishSubject() searchInput .debounce(300.milliseconds, mainScheduler) .subscribe( onNext = { query -> println("Searching for: $query") // Perform search only after user stops typing } ) // Rapid typing simulation searchInput.onNext("h") // Dropped searchInput.onNext("he") // Dropped searchInput.onNext("hel") // Dropped searchInput.onNext("hell") // Dropped searchInput.onNext("hello") // Emitted after 300ms pause ``` -------------------------------- ### Coroutines Interoperability: Convert Suspend Functions to Single in Kotlin Source: https://context7.com/badoo/reaktive/llms.txt This code shows how to convert Kotlin suspend functions into Reaktive Single objects. This allows for reactive composition of asynchronous operations, such as network requests, using Reaktive's powerful operators. ```kotlin import com.badoo.reaktive.coroutinesinterop.singleFromCoroutine import com.badoo.reaktive.single.subscribe import com.badoo.reaktive.single.flatMap import com.badoo.reaktive.single.map import kotlinx.coroutines.delay suspend fun fetchUserAsync(id: Int): String { delay(1000) // Simulate network delay return "User $id" } suspend fun fetchOrdersAsync(user: String): List { delay(500) return listOf("Order1", "Order2", "Order3") } // Convert suspend function to Single val userSingle = singleFromCoroutine { fetchUserAsync(123) } userSingle .flatMap { user -> singleFromCoroutine { fetchOrdersAsync(user) } } .map { orders -> orders.joinToString() } .subscribe( onSuccess = { println("Orders: $it") }, onError = { println("Failed: ${it.message}") } ) ``` -------------------------------- ### Automatic Retry for Failed Operations - Kotlin Source: https://context7.com/badoo/reaktive/llms.txt Automatically retries failed operations a configurable number of times. This is useful for handling transient network errors or other temporary failures. It takes a 'times' parameter to specify the maximum number of retries. ```kotlin import com.badoo.reaktive.observable.observable import com.badoo.reaktive.observable.retry import com.badoo.reaktive.observable.subscribe var attempts = 0 val unstableOperation = observable { emitter -> attempts++ println("Attempt $attempts") if (attempts < 3) { emitter.onError(RuntimeException("Failed attempt $attempts")) } else { emitter.onNext("Success on attempt $attempts") emitter.onComplete() } } unstableOperation .retry(times = 3) .subscribe( onNext = { println("Result: $it") }, onError = { println("Finally failed: ${it.message}") }, onComplete = { println("Done") } ) // Output: Attempt 1 // Output: Attempt 2 // Output: Attempt 3 // Output: Result: Success on attempt 3 // Output: Done ``` -------------------------------- ### Create Completable for Side Effects - Kotlin Source: https://context7.com/badoo/reaktive/llms.txt Creates a Completable observable that performs an action and signals completion or error, without emitting any value. Use this when the outcome of an operation (success or failure) is important, but the return value is not. ```kotlin import com.badoo.reaktive.completable.completableFromFunction import com.badoo.reaktive.completable.completableOfEmpty import com.badoo.reaktive.completable.completableOfError import com.badoo.reaktive.completable.subscribe // Successful completion val saveOperation = completableFromFunction { // Save data to database println("Data saved successfully") } saveOperation.subscribe( onComplete = { println("Operation finished") }, onError = { println("Failed: ${it.message}") } ) // Output: Data saved successfully // Output: Operation finished // Empty completable (immediate completion) val immediate = completableOfEmpty() immediate.subscribe( onComplete = { println("Immediately complete") } ) // Error completable val failed = completableOfError(RuntimeException("Network error")) failed.subscribe( onComplete = { println("Done") }, onError = { println("Error: ${it.message}") } // Output: Error: Network error ) ``` -------------------------------- ### Combine Latest Values with combineLatest - Kotlin Source: https://context7.com/badoo/reaktive/llms.txt Combines multiple source Observables. It emits a value whenever any of the source Observables emits, using the latest value from each source. The combination function is applied to the latest values from all sources. ```kotlin import com.badoo.reaktive.observable.combineLatest import com.badoo.reaktive.observable.subscribe import com.badoo.reaktive.subject.publish.PublishSubject val firstName = PublishSubject() val lastName = PublishSubject() val age = PublishSubject() // Combine two sources combineLatest(firstName, lastName) { first, last -> "$first $last" }.subscribe( onNext = { println("Full name: $it") } ) firstName.onNext("John") // No output yet (lastName missing) lastName.onNext("Doe") // Output: Full name: John Doe firstName.onNext("Jane") // Output: Full name: Jane Doe // Combine three sources combineLatest(firstName, lastName, age) { first, last, a -> "$first $last, age $a" }.subscribe( onNext = { println(it) } ) ``` -------------------------------- ### Merge Multiple Streams with merge - Kotlin Source: https://context7.com/badoo/reaktive/llms.txt Merges multiple Observables into a single Observable. Elements are emitted from the merged Observable as soon as they are emitted by any of the source Observables. The order of elements from different sources is interleaved based on their arrival time. ```kotlin import com.badoo.reaktive.observable.merge import com.badoo.reaktive.observable.observableOf import com.badoo.reaktive.observable.subscribe val source1 = observableOf(1, 2, 3) val source2 = observableOf(10, 20, 30) val source3 = observableOf(100, 200, 300) // Merge into single stream listOf(source1, source2, source3) .merge() .subscribe( onNext = { println(it) } // Elements interleaved based on timing ) // Vararg version merge(source1, source2, source3) .subscribe( onNext = { println(it) } ) ``` -------------------------------- ### Transform Elements with map - Kotlin Source: https://context7.com/badoo/reaktive/llms.txt Transforms each element emitted by an observable using a provided mapping function. This is a fundamental operator for modifying the data stream. It can be chained for multiple transformations. ```kotlin import com.badoo.reaktive.observable.observableOf import com.badoo.reaktive.observable.map import com.badoo.reaktive.observable.subscribe data class User(val id: Int, val name: String) val numbers = observableOf(1, 2, 3, 4, 5) val doubled = numbers.map { it * 2 } doubled.subscribe( onNext = { println(it) } // Output: 2, 4, 6, 8, 10 ) // Chaining transformations val users = observableOf( User(1, "Alice"), User(2, "Bob"), User(3, "Charlie") ) users .map { it.name } // Extract name .map { it.uppercase() } // Convert to uppercase .subscribe( onNext = { println(it) } // Output: ALICE, BOB, CHARLIE ) ``` -------------------------------- ### Filter Elements with Predicate - Kotlin Source: https://context7.com/badoo/reaktive/llms.txt Filters elements from an Observable based on a provided predicate function. Only elements for which the predicate returns true are emitted. This operator is useful for selecting specific data points from a stream. ```kotlin import com.badoo.reaktive.observable.observableOf import com.badoo.reaktive.observable.filter import com.badoo.reaktive.observable.subscribe val numbers = observableOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // Filter even numbers numbers .filter { it % 2 == 0 } .subscribe( onNext = { println(it) } // Output: 2, 4, 6, 8, 10 ) // Combine with map data class Product(val name: String, val price: Double, val inStock: Boolean) val products = observableOf( Product("Laptop", 999.99, true), Product("Phone", 599.99, false), Product("Tablet", 399.99, true) ) products .filter { it.inStock } // Only in-stock items .filter { it.price < 500 } // Under $500 .map { it.name } .subscribe( onNext = { println("Available: $it") } // Output: Available: Tablet ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.