Created
July 27, 2015 10:14
-
-
Save omarmiatello/f95da7398fc1d6fe9089 to your computer and use it in GitHub Desktop.
Helper class for handle rx.Subscription in Activity/Fragment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package it.justonetouch.utils | |
import rx.Observable | |
import rx.Subscription | |
import rx.android.schedulers.AndroidSchedulers | |
import rx.schedulers.Schedulers | |
import rx.subscriptions.CompositeSubscription | |
import kotlin.properties.Delegates | |
/** | |
* Created on 14/07/15, 13:02 | |
*/ | |
// Handle subscriptions for no memory-leak. Thanks to http://blog.danlew.net/2014/10/08/grokking-rxjava-part-4/ | |
class SubscriptionManager() { | |
private var hasComposite: Boolean = false | |
private var compositeSubscription: CompositeSubscription by Delegates.notNull() | |
fun getValidCompositeSubscription(): CompositeSubscription { | |
if (!hasComposite || compositeSubscription.isUnsubscribed()) { | |
hasComposite = true | |
compositeSubscription = CompositeSubscription() | |
} | |
return compositeSubscription | |
} | |
fun handle(subscription: Subscription?) { | |
getValidCompositeSubscription().add(subscription) | |
} | |
fun unsubscribe() { | |
if (hasComposite) compositeSubscription.unsubscribe() | |
} | |
} | |
fun <T> Observable<T>.likeAsyncTask() = cache() // TODO Check if it is really needed | |
.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment