Amrmsmb
Amrmsmb

Reputation: 1

How to use Maybe operator to check nullability

In the code below, I want to confirm or assert that the returned object or emission from the map operator is not null or if it is null - empty() should be returned. Please let me know if it is correct or not..

Activity

companion object {
    fun create(): Maybe<WikiApiService>? {
        return Single.just(
            Retrofit.Builder()
                .addCallAdapterFactory(
                    RxJava2CallAdapterFactory.create()
                )
                .addConverterFactory(
                    GsonConverterFactory.create()
                )
                .baseUrl("https://en.wikipedia.org/w/")
                .build()
        )
            .map { retrofit -> retrofit.create(WikiApiService::class.java) }
            .toMaybe()
            //.toObservable()
    }
}

Upvotes: 1

Views: 5312

Answers (2)

toantran
toantran

Reputation: 1819

I would recommend to go with a Optional wrapper like Guava implementation

or implement it a simple way like:

class Optional<T>(private val value: T? = null) {

    fun getValue(): T {
        if (value != null) {
            return value
        } else {
            throw ValueUnavailableException(this.logTag())
        }
    }

    private inline fun <reified T> T.logTag() = T::class.java.simpleName

    fun toNullable(): T? = this.value

    fun hasValue(): Boolean {
        return value != null
    }
    class ValueUnavailableException(className: String = "") : Exception("The optional value for $className is null")
}

In your stream usage, use


.filter { optionalObject.hasValue() }

Upvotes: 2

Damon Baker
Damon Baker

Reputation: 907

RxJava will not allow nulls inside the stream, so if map returns null, the stream will be terminated with an error event.

What you can do instead is replace map with flatMapMaybe and return either Maybe.just(service) or Maybe.empty() if the value is null. Then you can assert whether the result was successful or not in your subscribe callback, where onSuccess means the value was not null and onComplete means the value was null.

Two additional notes. The maybe your are returning should not have to be declared nullable, since that information will be captured inside the Maybe itself. However I'm not sure you need to be handling this null case anyway since as far as I can tell, retrofit.create shouldn't be returning null in the first place.

Upvotes: 2

Related Questions