Skip to content

2.x: emitting nulls from Observable.create() #4492

@marcin-kozinski

Description

@marcin-kozinski

It is not possible right now to create an observable that emits nulls using Observable.create(). Emitter's javadoc states @param value the value to signal, not null and in fact when I tried calling emitter.onNext(null) it is checked at runtime and results in a NullPointerException.

Can I get any insight as to why this decision has been taken? And why only in this place, as I believe it is still possible to emit null via for example Observable.just()?

It is a fairly common pattern when you want an observable that emits multiple "events" that don't carry any data. Usually then you create an Observable<Void> and emit nulls in onNext(). For example this is what I tried to write to get an observable of clicks on a view in Android (while @JakeWharton 's RxBinding doesn't have a 2.x release):

public static Observable<Void> clicks(final View view) {
    return Observable.create(emitter -> {
        MainThreadDisposable.verifyMainThread();

        view.setOnClickListener(ignored -> emitter.onNext(null)); // causes NullPointerException at runtime

        emitter.setDisposable(new MainThreadDisposable() {
            @Override
            protected void onDispose() {
                view.setOnClickListener(null);
            }
        });
    });
}

Should I use a different way of creating such observable? Or is there a different pattern altogether for this use case in 2.x?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions